所以我正在尝试使用XMLHTTPRequest来获取外部脚本来完成登录请求。
我得到的错误是XMLHttpRequest无法加载http:// / .php。 Access-Control-Allow-Origin不允许使用原点http:// *。
现在我对这篇文章非常熟悉了: XmlHttpRequest error: Origin null is not allowed by Access-Control-Allow-Origin
根据我的理解,我需要将其作为JSONP对象请求。问题是,我正在使用XMLHTTPRequest,并且无法使用jQuery库来实现这一点。
这是我在html页面中的代码,我正在尝试执行以下脚本:
<html>
<head>
<meta http-equiv="Access-Control-Allow-Origin" content="*">
<script language = "javascript" type="text/javascript" src="jquery-1.7.2.js">
</script>
<script language = "javascript" type="text/javascript" src="main.js">
</script>
<script type="text/javascript">
function show_prompt()
{
var name=prompt("User Name");
var password =prompt("Password");
var loginWorked = false;
if (name!=null && name!="") loginWorked = init(name,password);
if(loginWorked == true){
window.location = "Toolbar.html"
}
}
</script>
</head>
<body>
<input type="button" onclick="show_prompt()" value="Login" />
</body>
</html>
我主文件中的代码:
init函数:
function init(username,password){
//Initializes the toolbar.
init.user = username;
init.pass = password;
init.pass_hashed = sha256(init.pass);
var key = fetchKey(username);
init.pass_hashed += key;
init.pass_hashed = sha256(init.pass_hashed);
var loginParams = "login=1&pwd=" + init.pass_hashed + "&uname=" + init.user + "&LastKey=" + getKey();
loginReqReturn = send_request("http://data.nova-initia.com/login2.php","POST", loginParams);
if(loginReqReturn.responseText != "Error: Login Incorrect "){
return true;
}
else return false;
}
sendRequest方法:
function send_request(theURL, theMethod, theParams)
{
var theReq = new XMLHttpRequest();
theReq.overrideMimeType("application/json");
theReq.open(theMethod,theURL,false);
if(typeof(theParams) === "string")
{
theReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
}
else
{
theReq.setRequestHeader("Content-type", "application/json");
theParams = JSON.stringify(theParams);
}
if(_key) theReq.setRequestHeader("X-NOVA-INITIA-LASTKEY", _key);
if(theParams)
{
theReq.send(theParams);
}
setKey(theReq);
return theReq;
}
不是最有效的代码,但它至少在我在非HTML上下文中执行时起作用(我正在使用Google Chrome的工具栏,但需要使用html叠加层才能工作)。非常感谢任何帮助。
答案 0 :(得分:0)
我不确定你的确切问题是什么,但如果你知道使用JSONP就是你可以在不使用jQuery的情况下做到这一点的解决方案。以下是它的工作原理:http://en.wikipedia.org/wiki/JSONP
答案 1 :(得分:0)
如果是Google Chrome Extension,您可以在扩展程序清单中请求cross-origin XMLHttpRequest
requests的权限:
{
...
"permissions": [
"http://data.nova-initia.com/"
],
...
}