我删除了一个以前提出的问题,现在再次更简洁地问我对问题有更多的理解。AJAX:我如何解决需要同步请求的问题?
我有一个页面,使用大量的AJAX,并更新和动态填充内容(表单元素和div从其他表单元素返回的文本)。
我真的需要能够强制用户等待,直到AJAX请求处理完毕(例如,在他们完成提交一些值的文本字段后),然后才能继续。从我收集使用同步请求可能会导致浏览器挂等问题...
我还需要一个JavaScript函数,执行多个AJAX函数调用,但我也需要他们一次执行一个。目前使用异步调用会产生不可预知的结果......也许我会以错误的方式解决这个问题。有很多的代码,所以很难提供一个简短的例子,但我会试试下面:
从下面(它本身插入一个Ajax函数)动态地添加更多的表单元素到页面if它是第一次输入已被编辑(第一次内容被写入数据库...随后它只会更新现有的数据库条目,我不需要添加额外的表单项)
<form name='talkItemForm' id='talkItemFrom-<?php print $_POST[talkItemID]; ?>' class='talkItemForm' method='post'>
<input type='hidden' id='talkItemID' name='talkItemID' value='<?php print $_POST[talkItemID]; ?>'><input type='hidden' id='talkID' name='talkID' value='<?php print $_POST[talkID]; ?>'>
<input type='text' name='talkItemInput' id='talkItemInput' value='New Topic...' onblur=" updateTalkItem(this.parentNode, '<?php print $_POST[talkID]; ?>', '<?php print $_POST[talkItemID]; ?>'); isNewTalkItem('<?php print $_POST[talkID]; ?>', '<?php print $_POST[talkItemID]; ?>', '<?php print generateTalkItemID()+1; ?>','<?php print generateNoteID(); ?>'); "/>
</form>
调用:
function isNewTalkItem (talkID, talkItemID, newTalkItemID, newNoteID){
var url = "./wp-content/themes/twentyten/addBelowIfNew.php";
var poststr = "talkItemID=" + talkItemID;
http_request = false;
if (window.XMLHttpRequest) { // Mozilla, Safari,...
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType) {
// set type accordingly to anticipated content type
//http_request.overrideMimeType('text/xml');
http_request.overrideMimeType('text/html');
}
} else if (window.ActiveXObject) { // IE
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!http_request) {
alert('Cannot create XMLHTTP instance');
return false;
}
http_request.onreadystatechange = function(){
if (http_request.readyState == 4) {
if (http_request.status == 200 || http_request.status == 0) {
result = http_request.responseText;
//following code will note execute if this is not the first time this field has been edited...
if (result) {
// call to AJAX function that inserts a new <form>
newNote(newNoteID, talkItemID);
// another call to AJAX function that inserts a new <form>
newTalkItem(talkItemID, talkID);
}
} else {
alert('There was a problem with the request.');
}
}
}
http_request.open('POST', url, true);
http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http_request.setRequestHeader("Content-length", poststr.length);
http_request.setRequestHeader("Connection", "close");
http_request.send(poststr);
感谢您的回复。 1)如果使用jQuery更容易,我一定会这样做。 2)这听起来不错,谢谢。 3)也许我不需要这样做......但目前发生的情况是,只有来自某个AJAX请求的内容因为某种原因被插入。如果我在其中一个函数中发现任意随机值,那么看起来这两个请求中的内容都是在我点击ok后添加的...所以我认为这必须与在另一个函数之前完成执行的某个函数有关,并且以某种方式停止第二个功能从完成。对不起,如果这是令人困惑??! – 2010-11-23 19:05:42
如果您使用的某些变量是全局变量,我无法从您的代码中得知。如果它们是 - 那么多个ajax调用在返回数据时会填充相同的变量。这是一个显而易见的问题。 JQuery为多个Ajax调用提供了面向对象的解决方案,因此跟踪变量范围要容易得多。 – Mikhail 2010-11-23 19:17:52