0
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”时,它说它为空,我不知道为什么。

非常感谢任何帮助,在此先感谢!

4

2 回答 2

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()...

于 2013-11-13T09:31:12.330 回答
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);
}
于 2013-11-13T09:35:05.167 回答