我使用ajax从服务器获取数据,如下所示:(已编辑)
$(document).ready(function()
{
setInterval(function()
{
$.get('/forms/requestProcessor.php', function(data)
{
$("#shout").append(data.question+'<br>');
alert('Load was performed.');
},'JSON');
}, 5000); // 5 seconds
});
在 php 文件中,我发送如下数据:
while($row=mysql_fetch_array($result))
{
$question=$row['Question'];
$choice1=$row['Choice1'];
$choice2=$row['Choice2'];
$choice3=$row['Choice3'];
$choice4=$row['Choice4'];
$return_data->question = $question;
$return_data->choice1 = $choice1;
$return_data->choice2 = $choice2;
$return_data->choice3 = $choice3;
$return_data->choice4 = $choice4;
echo(json_encode($return_data));
}
它打印“未定义”。但是,如果我将浏览器直接指向 php 文件,它会以 json 格式正确显示数据
最佳答案
是的,最简单的方法可能是返回 json_encoded字符串。所以你的代码看起来像这样 php:
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . "GMT");
header("Cache-Control: no-cache, must-revalidate");
header("Pragma: no-cache");
header("Content-type: text/x-json");
echo json_encode($array);
exit(0);
JavaScript 看起来像这样:
$.get('/forms/requestProcessor.php', function(data)
{
....
}, 'json');
关于php - 如何解析$.get()函数获取的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4846916/