我有一個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