我有一个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中,所以我需要以某种方式删除那些我已经处理过的数组,这样我就可以只处理那些我还没有处理的新数组。
例如,log 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 );
}
});
}
}工作出色!:)
发布于 2011-09-16 03:23:51
好吧,你是在重复单独的json块。这就是为什么它不工作的原因..在同一个输出中有多个json块是无效的,所以任何解释json的东西都会被吐出来。相反,将这些数组添加到“master”数组中,并在脚本的末尾输出。例如,
$array = array();
while(loop) {
array_push($array, array( 'type' => 1, 'name' => $stringVar, 'id' => $id ));
}
echo json_encode($array);这应该会给你一些类似于..。
[
{"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"}
]哪个是有效的
发布于 2011-09-16 03:22:46
把你的数组放在另一个数组中,这样你就有了一个二维数组...然后将其设置为json
https://stackoverflow.com/questions/7436246
复制相似问题