How can I pass parameters to a jQuery $.getJSON ca

2019-02-04 07:16发布

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)
});

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)A callback function that is executed if the request succeeds.

How can I pass 1 or more parameters to a callback method?

5条回答
神经病院院长
2楼-- · 2019-02-04 07:53

If you want to use locationType (whose value is 3) in the callback, simply use

function(results) { .....

thanks to closures, locationType will be automatically available in the callback.

查看更多
三岁会撩人
3楼-- · 2019-02-04 08:00

Could try:

function getResults(locationType) {
    $.getJSON(url, {p1:'xxx', p2: 'yyy'}, function(results) {
        searchResults(results, locationType)
    });
}
查看更多
你好瞎i
4楼-- · 2019-02-04 08:03

You could use the .ajax method:

var locationType = 3;
var url = 'blah blah blah' + '&locationType=' + locationType;
$.ajax({
    url: url,
    context: { lt: locationType },
    success: function(results) {
        searchResults(results, this.lt);    
    }
});
查看更多
Animai°情兽
5楼-- · 2019-02-04 08:04

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 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)
});
查看更多
乱世女痞
6楼-- · 2019-02-04 08:16

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.

查看更多
登录 后发表回答