我对javascript json有问题。我可以从 ajax 帖子中获取值。
这样的脚本。
<script> function makeAjaxCall()
{
$.ajax({
type: "post",
data: $('#form1').serialize(),
url: "http://localhost/SPKM/new_file.php",
cache: false,
success: function(json){
var obj = jQuery.parseJSON(json);
var r = obj['STATUS'];
alert(r);
}
});
}
</script>
和这样的形式..
<form name="form1" id="form1">
<input type="text" name="value" id="value">
<input type="button" name="Submit" onkeypress="makeAjaxCall()">
</form>
而new_file.php是这样的..
<?
$query = "SELECT sum(in)-sum(out) AS total FROM $tableName";
$result = mysql_query($query);
while($row = mysql_fetch_array($result))
{
$phpVar = array("STATUS",$row['total']));
echo json_encode($phpVar);
}
?>
当我单击按钮时,结果是未定义的。感谢您的帮助..
你的数组将是结构的
[0] => "STATUS"
[1] => somevalue
如您所见,没有索引"STATUS",因此obj['STATUS']
将返回未定义。要么在数组创建中添加=>
,要么采用 obj 的第一个索引。
未定义,因为 u 数组不是关联映射。
<?php
$array = array('status' => $row['total']);
?>
js
$.ajax({
type: "post",
data: $('#form1').serialize(),
url: "http://localhost/SPKM/new_file.php",
cache: false,
success: function(json){
console.log( json.STATUS );
}
});
.php
while($row = mysql_fetch_array($result)) {
echo json_encode(array(
"STATUS"=> $row['total']
));
}