How can I pass parameters to a jQuery $.getJSON callback method?

前端 未结 5 2103
走了就别回头了
走了就别回头了 2020-12-29 23:50

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

相关标签:
5条回答
  • 2020-12-30 00:22

    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);    
        }
    });
    
    0 讨论(0)
  • 2020-12-30 00:24

    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.

    0 讨论(0)
  • 2020-12-30 00:27

    Could try:

    function getResults(locationType) {
        $.getJSON(url, {p1:'xxx', p2: 'yyy'}, function(results) {
            searchResults(results, locationType)
        });
    }
    
    0 讨论(0)
  • 2020-12-30 00:36

    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)
    });
    
    0 讨论(0)
  • 2020-12-30 00:39

    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.

    0 讨论(0)
提交回复
热议问题