等待Ajax完成其他function
我正在使用Ajax更新页面中的一些值。 然后,在完成之后,我需要使用该值来执行其他function。
我将一个函数放在另一个函数之后,但即使这样,第二个函数也没有等待Ajax完成。
$(document).ready(function(){ $(".data").blur(function(){ var id = $(this).attr('id'); var value = $(this).html(); var ad = id.split(';'); Update(valor, id); Function2(ad[1]); }); }); function Update(value, id){ if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else { // code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("div_table").innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET","update.php?value="+value+"&id="+id,true); xmlhttp.send(); } function Function2(ad){ var name_1 = $("#name_1").html(); //This part is updated inside a by the Ajax function $('#'+ad).html(name_1); }
使用jQuery Ajax实际上非常简单。
$.ajax({ url:"data/retrieve", success:function(result){ //call your function Function2(result); }});
在这里查看jQuery Ajax文档: http : //api.jquery.com/jquery.ajax/
编辑 :由于您使用GET作为请求类型,为什么不使用jQuery.get? 在这里,您可以使用此代码。 简单干净。
此外,如果适合您,请不要忘记将此标记为答案。 我们不希望StackOverflow的答案更少,我们呢?
$(document).ready(function(){ $(".data").blur(function(){ var id = $(this).attr('id'); var value = $(this).html(); var ad = id.split(';'); Update(value, id); }); }); function Update(value, id){ $.get("update.php", {value: value, id: id}, function (data) { //call your function Function2(data); }); } function Function2(ad){ var name_1 = $("#name_1").html(); //This part is updated inside a by the Ajax function $('#'+ad).html(name_1); }
您必须在处理function2
内部调用function2
,该函数位于您分配给onreadystatechange
的函数内部。
另外,我建议使用jQuery来进行ajax调用,因为它的API更简单,跨浏览器。 有关示例,请参阅jQuery.ajax()
的文档: http : //api.jquery.com/jquery.ajax/
我通常使用的最佳解决方案是带有return语句的ajax函数
function ajax_func(value,id) { if (window.XMLHttpRequest) AJAX=new XMLHttpRequest(); else AJAX=new ActiveXObject("Microsoft.XMLHTTP"); if (AJAX) { AJAX.open("GETT", "update.php", false); AJAX.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); AJAX.send("value="+value+"&id="+id); return AJAX.responseText; } else return null; }
您需要做的就是获得结果并执行其他function
var Result = ajax_func("value","id"); new_func();