我正在开发这个chrome扩展,我在Django上有后端。我正在做一个XMLHttpRequest POST来登录用户。当我在'DOMContentLoaded'上调用该函数时,它可以工作。但是,当我按下按钮时,它不起作用。
以下是javascript代码:
function login(){
//alert("hello");
var http = new XMLHttpRequest();
var url = "someURL";
//var email = document.getElementById("email").value;
//var password = document.getElementById("password").value;
var params = "email=someEmail&password=Password";
//alert(params);
//var params = "email=" + email + "&password=" + password;
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {
//alert(http.responseText);
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(params);
}
现在,当我这样做时:
document.addEventListener('DOMContentLoaded', function(){
login();
});
有效。点击扩展程序后,我收到了成功消息。
然而,当我这样做时:
document.addEventListener('DOMContentLoaded', function(){
document.getElementById("btn").addEventListener("click", login);
});
它不起作用。
以下是popup.html
:
<html>
<head>
<script src="popup.js"></script>
</head>
<body>
<div id="content">
<p id="demo"></p>
<form>
<input type="email" id="email">
<input type="password" id="password">
<button id="btn">Login</button>
</form>
</div>
</body>
</html>
这是manifest.json
{
"manifest_version": 2,
"name": "payback",
"description": "payback.",
"version": "1.0",
"content_scripts": [
{
"matches": ["http://*/", "https://*/"],
"js": ["popup.js"]
}
],
"browser_action": {
"default_popup":"popup.html"
},
"permissions": [
"http://*/", "https://*/"
]
}
答案 0 :(得分:4)
删除行
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
XMLHttpRequest不允许设置这些标头,它们由浏览器自动设置。 Read this for more information
也可以使用
<input type="button" id="btn" value="Login"/>
而不是
<button id="btn">Login</button>
因为按钮会自行提交表单。
答案 1 :(得分:2)
默认情况下,点击<button>
即可提交表单(因为默认类型为submit
)。试试这个
<button id="btn" type="button">Login</button>