2

I'm trying to refresh the content of my cells of an table. Therefore, I have a JavaScript which contains an AJAX request to a .php file, which creates my content that I want to insert into my table via JavaScript. The .php files last command is something like echo json_encode($result);.

Back in the JavaScript it says:

var testarray = xmlhttp.response;
alert(testarray);

But the outut from the alert looks like:

{"1":{"1":"3","2":"0","3":"2","4":"0"}}{"1":{"1":"3","2":"0","3":"2","4":"0"},"2":{"1":"2","2":"1","3":"1","4":"1"}}...    

So it seems the variable testarray isn't handled as an array but as a string. I already tried var testarray = JSON.parse(xmlhttp.response), but this doesn’t work. Neither does eval() works.

I don't know what to do, so the response of my request becomes an object.

4

2 回答 2

1

您的 json 中有 2 个奇怪的东西:

  1. 这部分不是 json 有效的: ...}{... 两个对象应该用逗号分隔

  2. 符号是带有字符串索引的对象而不是带有 int 索引的数组,它应该类似于:[[1,2,3,4],[5,6,7,8]]

对于第 1 点。看起来你有一个连接许多 json 的循环

对于第 2 点。对象表示法可以用作数组,所以没关系

一些代码:

    //the folowing code doesn't work: }{ is not parsable
var a=JSON.parse('{"1":{"1":"3","2":"0","3":"2","4":"0"}}{"1":{"1":"3","2":"0","3":"2","4":"0"},"2":{"1":"2","2":"1","3":"1","4":"1"}}');

    //the folowing code work and the object can be used as an array
var a=JSON.parse('{"1":{"1":"3","2":"0","3":"2","4":"0"},"2":{"1":"2","2":"1","3":"1","4":"1"}}');
alert(JSON.stringify(a[1]));


    //the folowing code displays the real notation of a javascript array:
alert(JSON.stringify([1,2,3,4]));
于 2013-08-27T09:31:25.077 回答
0

我认为这里的问题可能是您的数组没有索引 0。

例如,如果你从服务器输出这个 - 它会产生一个对象:

$result = [];
for ($i = 1; $i < 5; $i++) $result[$i] = $i;
echo json_encode($result);      // outputs an object

如果你从服务器输出这个 - 它会产生一个数组:

$result = [];
for ($i = 0; $i < 5; $i++) $result[$i] = $i;
echo json_encode($result);     // produces an array

无论如何,即使您的服务器将数组输出为对象 - 您仍然应该能够在 javascript 中正常访问它:

var resp = xmlhttp.responseText,  // "responseText" - if you're using native js XHR
    arr = JSON.parse(resp);       // should give you an object
console.log(arr[1]);              // should give you the first element of that object
于 2013-08-27T09:09:37.733 回答