我如何传递参数到JQuery $ .getJSON回调方法?
我尝试使用 JQuery
通过 Ajax / $。getJSON
调用一些自定义API。我试图传递自定义值到Ajax回调方法,但该值不会被传递,实际上被覆盖。这是我的代码: -
I'm trying to use JQuery
to call some custom api via Ajax/$.getJSON
. I'm trying to pass a custom value into the Ajax callback method, but that value is not getting passed through and is actually getting overwritten. This is my code:-
var locationType = 3;
var url = 'blah blah blah' + '&locationType=' + locationType;
$("#loading_status").show();
$.getJSON(url, null, function(results, locationType) {
searchResults(results, locationType)
});
现在 locationType
的值使用Ajax的URL是 3
。但是在Ajax返回数据成功后, locationType
的值现在为 success
。这是因为回调的方法签名是:
now the value of locationType
BEFORE i call the url using Ajax is 3
. But after the Ajax returns the data successfully, the value for locationType
is now success
. This is because the method signature of the callback is:
callback(data,textStatus)如果
请求成功,则执行回调
函数。
callback(data, textStatus)A callback function that is executed if the request succeeds.
Hmmm。好。那么如何将一个或多个参数传递给回调方法?
Hmmm. Ok. so how can i pass 1 or more parameters to a callback method, please?
,只是引用你已经有的变量,像这样:
You don't need to pass it in, just reference the variable you already have, like this:
var locationType = 3;
var url = 'blah blah blah' + '&locationType=' + locationType;
$("#loading_status").show();
$.getJSON(url, null, function(results) {
searchResults(results, locationType)
});
也不需要传递 null
if你没有数据对象,它是一个可选参数,jQuery检查第二个参数是否是一个函数,所以你可以这样做:
Also there's no need to pass null
if you don't have a data object, it's an optional parameter and jQuery checks if the second param is a function or not, so you can just do this:
$.getJSON(url, function(results) {
searchResults(results, locationType)
});