Javascript 如何将参数传递给 jQuery $.getJSON 回调方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/3430380/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I pass parameters to a jQuery $.getJSON callback method?
提问by Pure.Krome
I'm trying to use jQuery to call some custom API via Ajax/$.getJSON. 
我正在尝试使用 jQuery 通过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:
我正在尝试将自定义值传递到 Ajax 回调方法中,但该值并未传递,实际上已被覆盖。这是我的代码:
var locationType = 3;
var url = 'blah blah blah' + '&locationType=' + locationType;
$("#loading_status").show();
$.getJSON(url, null, function(results, locationType) {
    searchResults(results, locationType)
});
The value of locationTypeBEFORE I call the URL using AJAX is 3. But after the call returns the data successfully, the value for locationTypeis now success. This is because the method signature of the callbackis:
的价值locationType在我请使用AJAX是URL 3。但是调用成功返回数据后,值为locationTypenow success。这是因为回调的方法签名是:
callback(data, textStatus)A callback function that is executed if the request succeeds.
callback(data, textStatus) 请求成功时执行的回调函数。
How can I pass 1 or more parameters to a callback method?
如何将 1 个或多个参数传递给回调方法?
采纳答案by Nick Craver
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)
});
Also there's no need to pass nullif 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:
此外,null如果您没有数据对象,则无需传递,它是一个可选参数,jQuery 检查第二个参数是否为函数,因此您可以这样做:
$.getJSON(url, function(results) {
    searchResults(results, locationType)
});
回答by Felix Kling
Warp in a function, e.g.
扭曲函数,例如
function getResults(locationType) {
    $.getJSON(url, null, function(results) {
        searchResults(results, locationType)
    });
}
But in you specific situation you don't even have to pass it, you can access the value directly in the callback.
但是在您的特定情况下,您甚至不必传递它,您可以直接在回调中访问该值。
回答by Darin Dimitrov
回答by Pekka
回答by user6450793
Could try:
可以试试:
function getResults(locationType) {
    $.getJSON(url, {p1:'xxx', p2: 'yyy'}, function(results) {
        searchResults(results, locationType)
    });
}

