首页 > 解决方案 > 通过服务器路径访问 json 对象时获取 xmlhttp 响应为空

问题描述

我有一个 js 函数,它转到一个 spring 控制器类,它返回一个带有如下数据的 json 对象:

 {"prop1":"val1",
 "prop2":"val2"}

js 函数类似于:

 accessValue(a,b,c){

  var xmlhttp = new XMLHttpRequest();
       alert("This works 1");
       xmlhttp.onreadystatechange = function() {
           alert("This works 2");
              if (xmlhttp.readyState == XMLHttpRequest.DONE) { 
                  alert("This works 3" + xmlhttp.status);//line 1
              if (xmlhttp.status == 200) {
                   var jsonobj = JSON.parse(this.responseText); //line 1
                   alert("Hi ");
                   document.getElementById(b).innerHTML = jsonobj.prop1;
                   document.getElementById(c).innerHTML = jsonobj.prop2;
                   console.log(jsonobj.prop2);
              }
              else if (xmlhttp.status == 400) {
                    alert('There was an error 400');
              }

       }
     };
     xmlhttp.open("GET", a + "--spring controller class path --");
     xmlhttp.send(null);

}

在函数参数中,b 和 c 是 div id,我想用 json 对象中的数据更新它们。参数 a 是一个 URL,它附加了控制器类的 spring 路径,这个类返回运行完美的 json 对象。

在第 1 行,我将 xmlhttp.status 的状态设为 0,这是空响应。在线搜索后,我发现这可能会发生 bcz 该文件可以在本地正确访问,但通过服务器它没有发生。在 localhost 上使用相同的代码效果很好。有没有办法我可以使用正确的 http url 访问服务器上的这个 spring 控制器返回的 json 对象并解析数据以更新我的 div ?

标签: javascriptxmlspring-mvc

解决方案


推荐阅读