【发布时间】:2011-09-15 19:18:28
【问题描述】:
我有一个 javascript,它对启动循环的 PHP 脚本执行 AJAX 请求。此循环将数据返回到 javascript。我希望能够将数组从 PHP 脚本发送回 javascript,但这似乎无法正常工作。
主要是因为它有时会同时返回 2 个(或更多)数组。 我该如何让它工作?尝试搜索 JSON-help 但没有找到任何可以解释我的问题的内容。
在我的 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 javascript ajax arrays json