ajax JSON转储为数组

时间:2011-12-29 13:12:24

标签: ajax json responsetext

我有一个简单的ajax脚本,它从服务器返回一个json转储:

var request = false;
try {
request = new XMLHttpRequest();
} catch (trymicrosoft) {
try {
    request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (othermicrosoft) {
    try {
        request = new ActiveXObject("Microsoft.XMLHTTP");
    } catch (failed) {
        request = false;
    }
  }
}

function getIslandName() {
    var islandGroup = document.getElementById("id_island_group").value;
    var url = ".../find_island?island_group=" +  escape(islandGroup);
    request.open("GET", url, true);
    request.onreadystatechange = updatePage;
    request.send(null);
} 

function updatePage() {   
    if (request.readyState == 4)    
        if (request.status == 200)
            var data = JSON.decode(request.responseText);
            update(data);
            //document.getElementById("ajax_response").innerHTML = request.responseText;
        else if (request.status == 404)
            alert("Request URL does not exist");
        else
            alert("Error: status code is " + request.status);
}   


function update(data) {
    for (var key in data) {
        alert(data[key]);
    }
}

问题似乎出现在updatePage()函数中。如果我取消注释这一行:

//document.getElementById("ajax_response").innerHTML = request.responseText;

responseText json转储按预期显示。 e.g:

["Foo Island", "Bar Island", "Darwin Island"]

如果我在updatePage()函数中构造一个新的数据数组,如下所示:

function updatePage() {   
var string = "Something something ajax";
if (request.readyState == 4)
if (request.status == 200)
        var data=new Array(); 
        data[0]="Foo Island";       
        data[1]="Bar Island";
        data[2]="Darwin Island";
        update(data);
}

update()函数按预期工作,并提供预期的警报输出。

对于我做错的任何建议都将不胜感激。

0 个答案:

没有答案