Http请求通过AJAX发送了2次
Http request is sending 2 times through 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 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请求。我收到了2次Http响应。我已经写了console.log("更新表"),它显示了2次。我很困惑,为什么我收到了2次Http响应,而不是我只发送了1个请求?
您在请求过程中收到多个readyState事件。您希望在这里只在请求完成时收到通知。
用这个扩展你的处理程序:
if(xhr.readyState === 4 //ready) {
}
更新:最初的问题是通过简单的相等性检查(非类型化)解决的,这导致了在一些浏览器中readyState是包含number
的string typed field
的假设。
if(xhr.readyState == 4 //ready) {
}
您没有在onreadystatechange
处理程序中测试readyState
。每当状态发生变化时,该函数就会启动。当readyState未完成时,通常会中止函数(通过返回)。
xhr.onreadystatechange = function(ev){
if (this.readyState !== 4) {
return;
}
// ...
我认为问题在于您没有检查xhr的readyState值。onreadystatechange回调代码应该用if语句包装:
if (xhr.readyState === 4) {
// your code here...
}
只有当readyState为4时,请求才真正完成。
谨致问候,Udi
相关文章:
- 使用多个依赖项加载只进行一次AJAX调用
- readyState=4三次.Ajax-由警报引起
- 如何在下一次 AJAX 调用中访问从一个 AJAX 调用返回的变量
- 表单提交了两次(ajax和jquery)
- 在多次AJAX调用后暂停执行AJAX回调
- FB.api 仅在第一次 AJAX 调用页面时加载
- 一次 Ajax 调用中有 2 个 URL
- 反应组件调用了两次(AJAX调用异步)
- 如果通过 ajax 调用 PHP 页面需要一段时间才能运行/返回(并且它设置了会话变量),则第二次 ajax 调用会看到
- 加载动画在第二次 ajax 调用之前消失
- 角度表单提交两次(ajax get request)
- 如何避免多次AJAX调用
- 如何在点击超链接时触发第二次AJAX调用
- jQuery点击进行多次AJAX调用
- 在多次ajax调用后执行函数
- Javascript应用程序:糟糕的设计导致数百次ajax调用
- 在第一次ajax成功后用其他ajax调用函数
- Knockout可观察绑定仅在第一次ajax调用后更新
- live()、delegate()和on()在使用jQuery发出几次ajax请求后停止工作
- 在onTime函数jwplayer中只执行一次ajax请求