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

Json object successfully filled with xmlhttprequest suddenly is "null"

本文关键字:null 突然 对象 填充 xmlhttprequest Json 成功      更新时间:2023-09-26
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字符串:

[{"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"时,它说它是空的,我不知道为什么。

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

在代码中,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);
}
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();
}

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