javascript - 通过服务器路径访问 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 ?
解决方案
推荐阅读
- mysql - SQL IN 子句仅返回以逗号分隔的 ID 列表中具有第一个匹配项的行
- elasticsearch - 如何通过弹性聚合获得总词频?
- javascript - 为什么 PhpStorm 不显示所有 TSLint 规则?
- spring - 在没有 application.xml 的情况下连接 Bean 时如何理解注解 @ComponentScan 的工作?
- sql - 如何在不从现有表中选择的情况下使用“Proc SQL”创建表
- laravel - Laravel Varbox - 获取特定语言的可翻译模型属性值
- mysql - 如何解决“mysql工作台窗口中用户'root'@'localhost'的访问被拒绝”
- sql - 截断不正确的整数值“。”
- python - 如何向 rest api 端点发出 post 请求,并请求将我的表单保存在 django 的视图文件中?
- c++ - 在 boost/beast 中获取请求协议