[英]Callback inside AJAX success
Im trying to add an optional callback inside an AJAX successful execution, but I can't seem to get the callback to run when I want it to. 我试图在AJAX成功执行过程中添加一个可选的回调,但是我似乎无法让该回调在需要时运行。
heres and example of my AJAX code 这是我的AJAX代码示例
function someAjaxFunction(hosturl, callback){
$.ajax({
type: "GET",
url: hosturl,
data: {'something': 'code' },
dataType: 'json',
success: function(html){
var arr = $.map(html, function(val) { return val; });
if(arr[0] != 'false'){
console.log('1');
console.log('2');
if (callback) {
console.log('calling the callback')
callback();
}
console.log('3');
}else{
console.log('fail')
}
}
});
}
here is the callback and example of how the AJAX is being executed 这是如何执行AJAX的回调和示例
function thisIsACallBack(){
console.log("i'm a callback");
}
someAjaxFunction("some url", thisIsACallBack);
If I run this code the console outputs. 如果运行此代码,则控制台输出。
1
2
3
i'm a callback
I can even remove the callback if-condition all together and I would still get the same output. 我什至可以一起删除回调if条件,我仍然会得到相同的输出。
Also is here a better way to handle my Ajax return currently my response wrapped inside a json object. 这也是处理我的Ajax返回的更好的方法,当前我的响应包装在json对象中。 If the database can't find the object I have to place 'false' inside an array and convert it to a json object before echoing it back to ajax. 如果数据库找不到对象,那么我必须在数组中放置“ false”并将其转换为json对象,然后再将其回传给ajax。
Couse you have to pass your callback as string to your function 因为您必须将回调作为字符串传递给函数
someAjaxFunction("some url", thisIsACallBack); // <-- Wrong thisIsACallBack will be triggered after someAjaxFunction as some separate function call
like this 像这样
someAjaxFunction("some url", "thisIsACallBack()"); // <- Correct way
// Then call eval( callback ); inside Ajax success
....
success: function(html){
...
eval( callback );
}
your problem was that in case of this code someAjaxFunction("some url", thisIsACallBack);
您的问题是,在此代码的情况下someAjaxFunction("some url", thisIsACallBack);
it was triggering someAjaxFunction
then thisIsACallBack
function as you written someAjaxFunction
name not as string 它在您编写someAjaxFunction
名称而不是字符串时触发了someAjaxFunction
然后是thisIsACallBack
函数
UPDATE 更新
if you have to pass params to your callback your option is 如果您必须将参数传递给回调,则可以选择
someAjaxFunction("some url", function(param1){
thisIsACallBack(param1)
); } );
...
success: function(html){
...
callback( yourArray );
}
JavaScript has many ways how you can pass callbacks depends on your need JavaScript有多种方式可以传递回调取决于您的需要
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.