【发布时间】:2015-11-04 15:35:15
【问题描述】:
我的本地主机上运行着一个网络服务器。如果我从我的网络服务器加载我的网页,一切正常。我可以使用我的网络服务器打开一个 REST 会话。
JS代码:--
$(document).ready(function() {
var xhr = new XMLHttpRequest();
var open_str = "http://localhost:8080/vscp/rest?user=admin&password=d50c3180375c27927c22e42a379c3f67&format=json&op=1";
xhr.open("GET", open_str, true);
xhr.onreadystatechange = function() {
alert(xhr.readyState + "" + xhr.status);
if (xhr.readyState == 4 && xhr.status == 200) {
alert("session opend success");
var json = JSON.parse(xhr.responseText);
alert(JSON.stringify(json, null, 10));
}
}
xhr.send();
});
HTML 代码:--
<!DOCTYPE html>
<html>
<head>
<title>Hello jQuery</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="hello.js"></script>
</head>
<body>
<div>
<p class="greeting-id">Trying to open the REST session with vscpd </p>
</div>
</body>
</html>
现在,如果我从 D: 驱动器加载相同的 html 页面:--
file:///D:my_folder/htm_test.html
我收到以下错误“不存在‘Access-Control-Allow-Origin’标头”。我已经检查了 xhr.readyState 为 4 且 xhr.status 为 0 的 javascript 代码。
请建议对我的 javascript 代码进行哪些更改,这样,如果我使用 file:/// 直接从我的 D: 驱动器打开 html 文件,那么我的网络服务器也会正确打开 REST 会话。
========================== JSONP代码==================== ====
$(document).ready(function() {
var url = "http://localhost:8080/vscp/rest?user=admin&password=d50c3180375c27927c22e42a379c3f67&format=json&op=1";
function jsonpCallback(response) {
alert('success');
}
$.ajax({
url: url,
dataType: 'jsonp',
error: function(xhr, status, error) {
alert("error" + " " + error.message);
},
success: jsonpCallback
});
return false;
});
我得到的错误:-- 服务器正在发送正确的响应:-- {"success":true,"code":1,"message":"success","description":"Success","session-id":"e5a36e14b687c37b615dbc6a9506df5c","nEvents":0}
但是 ajax 调用给这个响应错误,即“Uncaught SyntaxError: Unexpected token :”
【问题讨论】:
标签: javascript rest xmlhttprequest