成功填充xmlhttprequest的Json对象突然变为“null”

时间:2013-11-13 09:26:13

标签: javascript json xmlhttprequest

function getOptionsData()
{
var xmlhttp = new XMLHttpRequest();

xmlhttp.onreadystatechange=function()
{
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
    {
        json_options = JSON.parse(xmlhttp.responseText);

    }
}
xmlhttp.open("GET", "getData.php", true);
xmlhttp.send();
}

“json_options”是一个全局变量,它应该填充XMLHttpRequest的responseText,它包含一个有效的json String:

[{"id":"3","model":"NZ\/","model1":"","tablenr":"1","tabkey":"SSG\/","length":"4","descript":"Schukostecker gerade","matchcode":"","price":"0","pricex":"0","code":"1","textnr":"0","artikelnr":"0","funktion":"Seite 1"},{"id":"4","model":"NZ\/","model1":"","tablenr":"1","tabkey":"SWS\/","length":"4","descript":"Schuko gewinkelt \/ angled 90 Grad","matchcode":"","price":"0","pricex":"0","code":"1","textnr":"0","artikelnr":"0","funktion":"Seite 1"}]

此时一切正常,json_options包含一个有效的json对象。

函数“getOptionsData”在函数“createOptionsTable”中被调用:

function createOptionsTable()
{
getOptionsData();
var element = null;

for(var i = 0; i < json_options.length; i++)
{
[...]

当我想在此时访问“json_options”时,它表示它为空,我不知道为什么。

非常感谢任何帮助,提前谢谢!

2 个答案:

答案 0 :(得分:0)

function getOptionsData()
{
var xmlhttp = new XMLHttpRequest();

xmlhttp.onreadystatechange=function()
{
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
    {
        json_options = JSON.parse(xmlhttp.responseText);
         for(var i = 0; i < json_options.length; i++)
        {
          [...]
        }
    }
}
xmlhttp.open("GET", "getData.php", true);
xmlhttp.send();
}

在您真正从ajax而不是for loop内部获得响应之后,您的createOptionsTable()应该执行...

答案 1 :(得分:0)

在您的代码中,getOptionsData();之后的代码在调用成功回调之前执行。所以你得json_options为空

试试这个

   function getOptionsData(callback)
   {
     var xmlhttp = new XMLHttpRequest();

     xmlhttp.onreadystatechange=function()
     {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
        {
           json_options = JSON.parse(xmlhttp.responseText);
           callback();

        }
     }
   xmlhttp.open("GET", "getData.php", true);
   xmlhttp.send();
 }


 function createOptionsTable()
 {
   var callback = function()
   {
        var element = null;
        for(var i = 0; i < json_options.length; i++)
        {
          [...]
         }
   }

   getOptionsData(callback);
}