[英]Callback in javascript ajax request
I have a function to handle an ajax request, with a callback. 我有一个函数来处理带有回调的ajax请求。
What this code does is that it sends a request, and writes the response inside a div
in my html page. 该代码的作用是发送请求,并将响应写入html页面的
div
中。 However i encounter problems with the callback, and i am not sure if the function works properly... 但是我在回调中遇到问题,我不确定函数是否正常工作...
So my question is about the 2 lines of code inside xmlhttp.onreadystatechange
and i have highlighted them. 所以我的问题是关于
xmlhttp.onreadystatechange
的两行代码,我已经突出了它们。
Code: 码:
function check_if_over(callback) {
//first i collect some variables from the UI
var val1 = $('#timer').text(),
val2 = $('#work').val();
var val5=val1.split(":",1);
//I initialize the xmlhttp object
xmlhttp=GetXmlHttpObject();
if (xmlhttp==null)
{
alert ("Your browser does not support Ajax HTTP");
return;
}
xmlhttp.onreadystatechange = function() {
//*****my question is about this part inside the "if"
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
document.getElementById('content0').innerHTML=xmlhttp.responseText;
callback.call(xmlhttp.responseText);
}
};
xmlhttp.open('GET','Controller?action=check&timer='+val5+'&work='+val2);
xmlhttp.send();
}
So my question is, if the xmlhttp.onreadystatechange
works properly like that, performing the task of (a) writing the appropriate code inside my div, and (b) performing the callback. 所以我的问题是,如果
xmlhttp.onreadystatechange
像这样正常工作,请执行以下任务:(a)在div中编写适当的代码,以及(b)执行回调。 Thanks! 谢谢!
EDIT: 编辑:
So after that i do this thing, and i see that it does my prints in a non-expected way, as it skips the first print on the first iteration of this code, and makes it exactly on the time for the second iteration like that: 因此,在执行此操作之后,我发现它以一种非预期的方式进行打印,因为它会跳过此代码的第一次迭代中的第一次打印,并完全按照第二次迭代的时间进行打印:
point 2
点2
point 2
点2
(small wait)
(稍等)
point 1
点1
(I am basically alternating between 2 states every 1 minute, so i use this to check asynchronously something in the server-side. So this is where the checking happens.) (我基本上每1分钟在2个状态之间交替,所以我用它来异步检查服务器端的某些内容。所以这是检查的地方。)
check_if_over(function() {
alert("point 1");
over = document.getElementById("value_ok").firstChild.nodeValue;
}
alert("point 2");
EDIT 2: 编辑2:
It seems that with jquery it works perfectly, 似乎通过jquery可以完美运行,
point 2
点2
(small wait)
(稍等)
point 1
点1
point 2
点2
(small wait)
(稍等)
etc..
等等..
If you're already using jQuery why not use jQuery's $.get
function? 如果您已经在使用jQuery,为什么不使用jQuery的
$.get
函数?
function check_if_over(callback) {
//first i collect some variables from the UI
var val1 = $('#timer').text(),
val2 = $('#work').val(),
val5 = val1.split(":",1);
$.get('Controller?action=check&timer='+val5+'&work='+val2, function(data) {
$('#content0').html(data);
callback.call(data);
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.