【发布时间】:2012-04-30 10:00:53
【问题描述】:
所以我正在尝试获取外部脚本以使用 XMLHTTPRequest 完成登录请求。
我得到的错误是 XMLHttpRequest 无法加载 http:///.php。 Access-Control-Allow-Origin 不允许 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>
我的主文件中的代码:
初始化函数:
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 覆盖才能工作)。非常感谢任何帮助。
【问题讨论】:
-
你认为你只能用 jQuery 做这些类型的请求吗?
标签: javascript html xmlhttprequest