【发布时间】:2012-06-06 15:52:23
【问题描述】:
下面的代码有问题,每当我尝试从网站请求 JSON 数据时,我总是会得到响应代码 0。有人知道为什么吗?如果我要访问该网站,我只需输入正确的登录信息即可获取数据。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="Base64.js" type="text/javascript"></script>
<script type="text/javascript">
function alertContents(HTTPobj) {
if (HTTPobj.readyState == 4) {
// everything is good, the response is received
if ((HTTPobj.status == 200) || (HTTPobj.status == 0)) {
// FIXME: perhaps a better example is to *replace* some text in the page.
var htmlDoc = document.createElement('div'); // Create a new, empty DIV node.
htmlDoc.innerHTML = HTTPobj.responseText; // Place the returned HTML page inside the new node.
alert("The response was: " + HTTPobj.status + HTTPobj.responseText);
//var jsonData = eval('(' + HTTP.responseText + ')');
//parseJson(HTTP.responseText);
}
else {
alert('There was a problem with the request. ' + HTTPobj.status + HTTPobj.responseText);
}
}
}
}
function makeBaseAuth(user,password) {
var tok = user + ':' + password;
var hash = Base64.encode(tok);
alert(hash);
return "Basic " + hash;
}
function getInput() {
var getUser = document.input.user.value;
var getPass = document.input.pass.value;
var logData = makeBaseAuth(getUser, getPass);
var url = 'http://www.tt-galaxi.com/thubrest/login';
// var url = 'http://www.tt-galaxi.com/thubrest/users/%@/trips',username;
// var url = 'http://www.tt-galaxi.com/thubrest/parkingbays';
var HTTPobj = new XMLHttpRequest();
HTTPobj.onreadystatechange = function () { alertContents(HTTPobj); };
var test = HTTPobj.open('GET', url);
HTTPobj.setRequestHeader('Authorization', logData);
HTTPobj.send();
}
</script>
</head>
<body>
<form name="input" action="">
Username: <input type="text" name="user" />
<br />
Password:<input type="text" name="pass" />
<br />
<input id="Button1" type="button" value="Submit" onclick="getInput()"/>
</form>
</body>
</html>
【问题讨论】:
-
你用的是什么浏览器?控制台上是否有任何错误?
-
我不喜欢纯 javascript,但如果你使用 jQuery 的 post 函数,它会让你的生活更轻松
-
我尝试过 IE,FF,Chrome,Opera ,它们都给出了相同的响应代码。我认为它与同源政策有关,但我不知道如何处理它。
-
您将无法跨域执行此操作,所以是的,这可能是问题所在。您需要在本地代理它(使用将查询作为本地资源执行的服务器脚本)或使用 JSONP 接口(如果端点支持)。
-
我在 IIS 7.0 上托管的本地计算机上运行上述代码,这是否构成跨域?
标签: javascript