下面的 js 文件test
.js` 在我的 html 中运行良好。
function sendData()
{
var formData = new FormData( document.querySelector("form") );
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("post", "test.php",true);
xmlHttp.send(formData);
xmlHttp.onreadystatechange = function(){
if (xmlHttp.readyState == 4 && xmlHttp.status == 200){
alert(xmlHttp.responseText);
}
}
}
ob = document.getElementById("submit");
ob.addEventListener("click",sendData);
现在我想把它们分开
if (xmlHttp.readyState == 4 && xmlHttp.status == 200){
alert(xmlHttp.responseText);
在单个函数中。
我将 test1.js 重写为 test2.js。
var xmlHttp;
function ready(){
if (xmlHttp.readyState == 4 && xmlHttp.status == 200){
alert(xmlHttp.responseText);
}
}
function sendData()
{
var formData = new FormData( document.querySelector("form") );
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("post", "test.php",true);
xmlHttp.send(formData);
xmlHttp.onreadystatechange = ready;
}
ob = document.getElementById("submit");
ob.addEventListener("click",sendData);
test2.js
遇到错误信息:
test2.js:4 Uncaught TypeError: Cannot read property 'readyState' of undefined
at XMLHttpRequest.ready (test2.js:4)
另一个问题:以下语句的正确顺序是什么?
我看过一些材料写如下:
xmlHttp.open("post", "test.php",true);
xmlHttp.send(formData);
xmlHttp.onreadystatechange = function(){ }
还看到了其他材料:
xmlHttp.onreadystatechange = function(){ }
xmlHttp.open("post", "test.php",true);
xmlHttp.send(formData);
xmlhttp.open("POST", "Demo", true);
xmlhttp.onreadystatechange=myCallBack;
xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");
xmlhttp.send("FirstName=Nat&LastName=Dunn");