我正在将数据从 PHP 发送到 jQuery。一切工作正常,除了我想从数据库发送总行数。
我剥离了很多其他东西来解决本质问题。
PHP 代码:
header('Content-type: text/json');
header('Content-type: application/json');
$rows = array with the data; That is working fine
$total=mysql_num_rows($RSList);
$total_data=array("total"=>$total);
array_push($data,$total_data,$rows);
echo json_encode($data);
jQuery 代码:
$.getJSON("..url..", function( data ) {
var data_array = eval(data);
$.each(data_array[0], function(i, item ) {
console.log(item)
});
});
浏览器中显示的结果是:
[{"total":532},[{"product_id":"1",.... }]]
532 是来自 mysql_num_rows()
控制台: 空字符串
我尝试了以下方法:
如果我在 PHP 中手动设置总计值:
$total=100;
浏览器中显示的结果是:
[{"total":100},[{"product_id":"1",.... }]]
java控制台: 100
如果我在 PHP 中转换字符串中的值:
$total="(".$totalRows_RSList.")";
浏览器中显示的结果是:
[{"total":"(532)"},[{"product_id":"1",.... }]]
控制台: ()
我还尝试过 intval
、number_format
和 strval
但没有成功。
非常非常奇怪还是?
更新: 我已经按照建议修改了代码,但仍然存在同样的问题:
PHP:
echo json_encode(array('total' => $total, 'rows' => $rows));
java脚本:
$.getJSON( "..url..", function( data ) {
console.log( data )
$.each( data.rows, function(i, item ) {...}
})
浏览器:
{"total":532,"rows":[{"product_id":"567",...}]}
控制台:
Object { rows=[99], total=""}
最佳答案
您不需要传递总行数,只需获取解析的 JSON 对象的长度即可。
jQuery 代码:
$.getJSON('...url...', function(data){
console.log(data.length);
}
PHP 代码:
header('Content-type: text/json');
header('Content-type: application/json');
$rows = array_with_the_data; //That is working fine
echo json_encode($rows);
关于javascript - 使用 PHP JSON 编码将数据发送到 jQuery getJSON 的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21648950/