Javascript Http请求通过AJAX发送了2次
我的AJAX代码如下所示:Javascript Http请求通过AJAX发送了2次,javascript,php,ajax,Javascript,Php,Ajax,我的AJAX代码如下所示: data = new FormData(); // data=""; paths = ""; // Create a new HTTP requests, Form data item (data we will send to the server) and an empty string for the file paths. xhr = new XMLHttpRequest(); // Set how to han
data = new FormData();
// data="";
paths = "";
// Create a new HTTP requests, Form data item (data we will send to the server) and an empty string for the file paths.
xhr = new XMLHttpRequest();
// Set how to handle the response text from the server
xhr.onreadystatechange = function(ev){
//console.debug(xhr.responseText);
// console.log("success"+xhr.responseText);
try{
console.log($.parseJSON(xhr.responseText));
var data=$.parseJSON(xhr.responseText);
if(data.success=="yes"){
projectCounter++;
var projectName=$.parseJSON(data.arguments);
console.log(projectName.projectName);
console.log('update table');
if(projectCounter==2){
UploadComplete(projectName.projectName);
}
}
}
catch(e){}
};
// Loop through the file list
for (var i in files){
// Append the current file path to the paths variable (delimited by tripple hash signs - ###)
paths += files[i].webkitRelativePath+"###";
// Append current file to our FormData with the index of i
data.append(i, files[i]);
};
// Append the paths variable to our FormData to be sent to the server
// Currently, As far as I know, HTTP requests do not natively carry the path data
// So we must add it to the request manually.
data.append('paths', paths);
// console.log(paths);
// Open and send HHTP requests to upload.php
xhr.open('POST', "upload.php", true);
console.log(data);
xhr.send(this.data);
我面临的问题是它发送了两次http请求。我收到Http响应2次。我已经编写了console.log(“更新表”),它显示了2次。我很困惑为什么我收到2次Http响应,而不是只发送1个请求?您没有在
onreadystatechange
处理程序中测试readyState
。该功能将在每次状态更改时启动。readyState未完成时,通常会中止函数(通过返回)
您在请求过程中收到多个readyState事件。您希望在这里只在请求完成时收到通知 使用以下命令扩展处理程序:
if(xhr.readyState === 4 //ready) {
}
更新:
最初的问题是通过简单的相等性检查(非类型化)解决的,这导致了以下假设:在某些浏览器中,readyState是一个字符串类型的字段
,其中包含一个数字
if(xhr.readyState == 4 //ready) {
}
我认为问题在于您没有检查xhr的readyState值。 onreadystatechange回调代码应使用if语句包装:
if (xhr.readyState === 4) {
// your code here...
}
只有当readyState为4时,请求才实际完成
问候,,
Udi是否可以显示此代码运行的上下文?melc它向upload.php发送请求,后者上载数据upload.php脚本运行正常。我已经检查了它的IR xhr.readyState===4没有工作它没有显示任何东西如果您编写console.log(xhr.readyState)-删除if()会看到什么子句,以便为每次readyState更改调用…sir xhr.readyState===4不起作用它不显示anyhting@MuneemHabib-由于代码前面段落中描述的原因。sir this.readystate==我提醒一些文本,它几乎被调用了4次,但它不应该这样做。readystate函数将触发多次(4是很常见的),但它只应更改为状态4一次,因此它不应多次通过返回语句。
if (xhr.readyState === 4) {
// your code here...
}