[英]What I'm doing wrong when trying call back function
I am trying to use a call back function for this function in javascript 我正在尝试为此函数在JavaScript中使用回调函数
function Filtering_GetSite(siteElement) {
$.ajax({
type: "POST",
url: "samle.asmx/f1",
data: "",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var filtersitedetails = response.d;
var appendItem = "";
$(siteElement).empty();
$.each(filtersitedetails, function (index, Filtering_GetSiteInfo) {
var activeappend = "";
var id = Filtering_GetSiteInfo.id;
var site = Filtering_GetSiteInfo.site;
activeappend = "<option value=" + id + ">" + site + "</option>";
appendItem += activeappend;
});
$(siteElement).prepend('<option disabled="disabled" selected="selected" value="">Select Site</option>');
$(siteElement).append(appendItem);
},
error: function (response) {
alert("error in Filtering_GetSite");
}
});
}
and this is how I call the function and trying to use call back function 这就是我调用该函数并尝试使用回调函数的方式
Filtering_GetSite("#txt-site-name", function () {
alert('ok')
Dashboard_GetAgentInfo(agentParam,agentElement);
});
but the problem is it doesn't go to the alert when the function is finished. 但是问题是,功能完成后,它并没有进入警报状态。 How can I do this?
我怎样才能做到这一点?
That is because you do not seem to pass and invoke that method when the ajax
invokes successfully. 那是因为当
ajax
成功调用时,您似乎并没有传递和调用该方法。
First you will have to change the method signature of Filtering_GetSite
to accept a 2nd parameter which in this case is the callback
and then when the ajax
is a success you just invoke it. 首先,您必须更改
Filtering_GetSite
的方法签名以接受第二个参数,在这种情况下,该参数是callback
,然后,当ajax
成功执行时,您只需调用它即可。
function Filtering_GetSite(siteElement, callback) {
...
success: function() {
....
callback();
}
...
}
You haven't set your callback parameter into your Filtering_GetSite
function. 您尚未在
Filtering_GetSite
函数中设置回调参数。 eg 例如
function Filtering_GetSite(siteElement, callback) {
}
You can then call the callback with callback()
where you want it to fire. 然后,可以在希望触发的地方使用
callback()
调用该回调。 For example within the success
block; 例如在
success
块内;
This is a wrap. 这是一个包裹。
You need to specificy a second parameter for a callback function 您需要为回调函数指定第二个参数
I also added a condition so when you omit the second parameter it will check the callback
if its a function or not so you can call the function just Filtering_GetSite(sample)
insted of Filtering_GetSite(sample,function(){})
我还添加了一个条件,以便当您省略第二个参数时,它将检查
callback
是否是函数,因此您可以仅在由Filtering_GetSite(sample,function(){})
插入的Filtering_GetSite(sample)
调用该函数。
function Filtering_GetSite(siteElement, callback) {
if (typeof (callBack) == "function") {
callBack();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.