gpt4 book ai didi

javascript - jQuery 数组问题

转载 作者:行者123 更新时间:2023-11-30 08:16:48 24 4
gpt4 key购买 nike

<?php
include_once('db.php');
$location = $_POST['location'];
$doctor = $_POST['doctor'];
$patient_id = $_POST['patient_id'];

if(($location != "") && ($doctor != "")) {
$sql = "select Name,Age,Gest_age,Weight from rop_form where Location = '".$location."' and Doctor = '".$doctor."' and Patient_id = '".$patient_id."'";
$result = mysql_query($sql);
$myresult = "";
while($row = mysql_fetch_array($result)) {
$myresult1['Patient_id'] = 'R'.$patient_id;
$myresult1['Name'] = $row['Name'];
$myresult1['Age'] = $row['Age'];
$myresult1['Weight'] = $row['Weight'];
$myresult1['Gest_age'] = $row['Gest_age'];
}
$myresult = json_encode($myresult1);
}
else {
$myresult .= "";
}
echo $myresult;
?>

这是我的 PHP 代码。

这是 jQuery 代码。

$("#patient_id").change(function() {
$.post("/diabetes/patient_detail_change.php",{ location:$("#location").val(),doctor:$("#doctor").val(),patient_id:$("#patient_id").val()} ,function(json_data) {
alert(json_data);
//var my_json = //{"Patient_id":"R00020","Name":"admin","Age":"12","Weight":"67","Gest_age":"2"//};
$.each(json_data, function(key,value) {
alert(key + ': ' + value);
if(key == 'Name'){ $("#name").val(value); }
if(key == 'Age'){ $("#age").val(value); }
if(key == 'Weight'){ $("#ropweight").val(value); }
if(key == 'Gest_age'){ $("#gest_age").val(value); }
});
});
});

警报(json_data);此行正确打印为

{"Patient_id":"R00006","Name":"admin","Age":"12","Weight":"67","Gest_age":"2"} 这是 jquery 所需的格式

但是出现的 .each 循环语句如下:alert(key + ': ' + value); 不会像 Patient_id : R00006 和 all 那样打印。但它会像 0 一样打印:{ 1:P 2:a 3:t 4:i ..可能是什么问题?

最佳答案

除了 Matt Ellen 的回答之外,$.each() 方法用于遍历 JavaScript 数组和类数组对象(具有长度属性)。 PHP 的关联数组(关键字-> 值)被转换为原生 JavaScript 对象。您可以改用 for...in 循环:

for (var key in json_data) { 
alert(key + ': ' + json_data[key]);
if(key == 'Name'){ $("#name").val(json_data[key]);}
if(key == 'Age'){ $("#age").val(json_data[key]);}
if(key == 'Weight'){ $("#ropweight").val(json_data[key]);}
if(key == 'Gest_age'){ $("#gest_age").val(json_data[key]);}
}

但您可能不需要循环。你可以只使用:

$.post (
"/diabetes/patient_detail_change.php",
{
location:$("#location").val(),
doctor:$("#doctor").val(),
patient_id:$("#patient_id").val()
},
function (json_data){
if ("Name" in json_data) { $("#name").val(json_data.Name);}
if ("Age" in json_data) { $("#age").val(json_data.Age);}
if ("Weight" in json_data) { $("#ropweight").val(json_data.Weight);}
if ("Gest_age" in json_data) { $("#gest_age").val(json_data.Gest_age);}
},
"json"
);

关于javascript - jQuery 数组问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2317819/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com