我从php文件中检索一个名为check_num.php的数组: -
check_num.php
<?php
include 'config.php';
session_start();
$VALUE = $_SESSION["some_session_variable"];
if(isset($_POST['default'])){
$ert = "SELECT * FROM table_name WHERE something = '$VALUE' ORDER BY p_id ASC ";
$qty = mysql_query($ert);
$fgh = mysql_num_rows($qty);
$ertz = "SELECT something, COUNT(something) FROM table_name WHERE something = '$VALUE'
AND something >= 1 GROUP BY p_id ORDER BY p_id ASC";
$qtyz = mysql_query($ertz);
$tyui = mysql_num_rows($qtyz);
$data = array(
"post" => $fgh,
"likes" => $tyui
);
echo json_encode($data);
} else {
echo "0";
}
?>
现在出现了jquery部分: -
<script>
$(document).ready(function(){
setInterval(function(){
var def = "one";
$.post("check_num.php", {'default': def }, function(response){
if(response != 0){
document.getElementById("total_array_count").innerHTML = response;
//document.getElementById("total_like_count").innerHTML = response.likes;
//document.getElementById("total_post_count").innerHTML = response.post;
------------------OR THIS Method-----------------
var my_array = response;
//var post_number = my_array["post"];
document.getElementById("total_array_count").innerHTML = my_array;
//document.getElementById("total_post_count").innerHTML = '<b>'+post_number+'</b>';
}
else {
document.getElementById("total_array_count").innerHTML='Error occured !';
}
});
},2500);
});
</script>
现在收到的输出是{"post":10,"likes":1}
,它是一个数组。但是,当我访问数组值response.post
或my_array["post"]
时,返回的值为undefined
。
我经历了这个: - http://www.w3schools.com/js/tryit.asp?filename=tryjs_array_object
也是这样的: - jQuery .val() returns undefined for radio button
跟着它但没有成功!
请纠正我的错误。
答案 0 :(得分:0)
在尝试访问值之前,对结果运行JSON.parse()
。结果以原始字符串形式出现,您必须先将其转换为对象。
result = JSON.parse(result);
或者,由于您已经在使用jQuery,因此可以使用jQuery的别名来实现该功能。
result = $.parseJSON(result);
它们本质上是一样的。