onreadystatechange状态函数是第二次调用,为什么?

时间:2018-02-19 04:50:45

标签: javascript arrays json ajax

我正在尝试在我的本地服务器上加载JSON文件,我创建了函数,名称是getServiceData,在这个函数中,我通过创建ajax调用来加载JSON文件,getServiceData函数返回对变量的响应,变量名是gserviceData。现在我在控制台中打印这个变量,首先它是未定义的'第二次自动打印数据。请尽量帮助我。

JavaScript(main.js):

function getServiceData() {   
  debugger;
  var xobj = new XMLHttpRequest();
  xobj.overrideMimeType("application/json");
  xobj.open('GET', 'data/service.json', true); // Replace 'my_data' with the path to your file
  xobj.onreadystatechange = function () {
    if (xobj.readyState == 4 && xobj.status == "200") {  
      debugger;
      // Required use of an anonymous callback as .open will NOT return a value but simply returns undefined in asynchronous mode
      alert("calling");
      console.log(xobj);
      return JSON.parse(xobj.response);
    }
  };
  xobj.send(null);  
}


var gserviceData = getServiceData();

JSON(service.json):

[   {
        "WS": "Web Strategy",
        "WD": "Web design"
    },
    {
        "WD": "Web Development",
        "WP": "Web Performence"
    },
    {
        "WE": "Web Enhancement",
        "WH": "Web Hosting"
    },
    {
        "WS": "Web Support",
        "WA": "Web Applications"
    },
    {
        "MA": "Mobile Applications",
        "CHS": "Could Hosting Services"
    },
    {
        "PDC": "Product Development Consulting",
        "SEO": "Search Engine Optimization"
    }
]

2 个答案:

答案 0 :(得分:0)

您好,您正在尝试返回完成ajax调用,但java脚本不等待ajax,因此它将自动返回undefined.So在这种情况下,您可以使用promise或回调函数。

  function getServiceData(callback) {   debugger;
                    var xobj = new XMLHttpRequest();
                        xobj.overrideMimeType("application/json");
                    xobj.open('GET', 'data/service.json', true); // Replace 'my_data' with the path to your file
                    xobj.onreadystatechange = function () {
                          if (xobj.readyState == 4 && xobj.status == "200") {  debugger;
                            // Required use of an anonymous callback as .open will NOT return a value but simply returns undefined in asynchronous mode
                            alert("calling");
                            console.log(xobj);
                             callback(JSON.parse(xobj.response));
                          }
                    };
                    xobj.send(null);  
                 }


  getServiceData(function (data) {
   ////Write your logic here
});

答案 1 :(得分:0)

我已经编辑了一下你的代码。应该是这样的。请记住,在处理异步操作时,结果可能需要一段时间,因此您需要在结果准备好时附加回调以执行。



function getServiceData(done) {
  var xobj = new XMLHttpRequest();
  xobj.overrideMimeType('application/json');
  xobj.open('GET', 'data/service.json', true);
  xobj.onreadystatechange = function () {
    if(xobj.readyState === 4 && xobj.status === '200') {
      return done(JSON.parse(xobj.responseText));
    }
    done(null);
  };
  xobj.send(null);  
}

function onDone(data) {
  console.log(data);
}

getServiceData(onDone);