如何将参数传递给 jQuery $.getJSON 回调方法? [英] How can I pass parameters to a jQuery $.getJSON callback method?
问题描述
我正在尝试使用 jQuery 通过 Ajax/$.getJSON
调用一些自定义 API.
I'm trying to use jQuery to call some custom API via Ajax/$.getJSON
.
我正在尝试将自定义值传递给 Ajax 回调方法,但该值并未传递,实际上已被覆盖.这是我的代码:
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
.但是在调用成功返回数据后,locationType
的值现在是 success
.这是因为回调的方法签名是:
The value of locationType
BEFORE I call the URL using AJAX is 3
. But after the call 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.
如何将 1 个或多个参数传递给回调方法?
How can I pass 1 or more parameters to a callback method?
推荐答案
不需要传入,直接引用你已有的变量,像这样:
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
,它是一个可选参数,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)
});
这篇关于如何将参数传递给 jQuery $.getJSON 回调方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!