我有一个JavaScript,可以对一个启动循环的PHP脚本执行AJAX请求。该循环将数据返回给javascript。我希望能够从PHP脚本发回数组回到JavaScript,但这似乎没有正常工作。如何通过JSON从AJAX请求获取PHP数组(循环)?
主要是因为它有时会同时返回2个(或更多)数组。 我如何得到这个工作?试图寻找JSON帮助,但没有找到任何解释我的问题。
在我的HTTP响应方法:
if(http.readyState == 3)
{
console.log(http.responseText);
var toBeEvaled = "(" + http.responseText + ")";
console.log(toBeEvaled);
var textout = eval(toBeEvaled);
console.log(textout.name);
}
我的PHP是这样的:
echo json_encode(array('type' => 1, 'name' => $stringVar, 'id' => $id));
日志1变为:
{"type":1,"name":"String1","id":"1000004"}
{"type":1,"name":"String2","id":"60220"}
正如你看到的,有2个阵列在那一个。 另一个问题是,新的数组被添加到http.responseText中,所以我需要摆脱那些已经处理的数据,以便只处理尚未处理的新数组。
例如,日志2如下所示:
{"type":1,"name":"String1","id":"1000004"}
{"type":1,"name":"String2","id":"60220"}
{"type":1,"name":"String3","id":"5743636"}
{"type":1,"name":"String4","id":"8555983"}
{"type":1,"name":"String5","id":"7732"}
{"type":1,"name":"String6","id":"92257"}
任何想法?
::::编辑::::
解决了它!做了以下..
PHP:
echo json_encode(array('type' => 1, 'name' => $stringVar, 'id' => $id)) . '%#%';
注意 '%#%' 结尾。
的Javascript:
var lastResponse = '';
function useHttpResponse()
{
if(http.readyState == 3)
{
// Get the original response before we edit it
var originalResponse = http.responseText;
// Replace the found last response in our original response with nothing(basically editing out the last response)
var newResponse = originalResponse.replace(lastResponse, '');
// Add our new response to the last response
lastResponse += newResponse;
var responses = newResponse.split("%#%");
$.each(responses, function(index, value){
if(value != '')
{
var textout = eval('(' + value + ')');
console.log('Name: ' + textout.name + ', ID: ' + textout.id);
}
});
}
}
工作优秀! :)
不幸的是PHP主回路需要大约7分钟跑,我想它7分钟后连续发送数据而不是1个大“块”。无论如何你会解决问题吗 – Tanax
不幸的是,如果你想连续发回数据,json可能不是要走的路。这是一个非常结构化的设置,据我所知,它没有任何'流式处理'格式。你可以做更好的自定义格式(即---- \ n $ jsondata \ n ----),你可以通过js读入(即:最后--- \ n(数据)\ n ----)然后解码每个块的内容。这有任何意义吗? – Stephen
我解决了! :)编辑第一篇文章,随时发表评论,如果这是一个不好的方法。它虽然工作完美。 – Tanax