使用 jQuery 在函数中返回 $.get 数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1639555/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 11:54:29  来源:igfitidea点击:

Return $.get data in a function using jQuery

jqueryxmlhttprequest

提问by Kai

I'm trying to call a function that contains jQuery code. I want this function to return the results of the jQuery statement. It is not working, and I'm trying to figure out why.

我正在尝试调用一个包含 jQuery 代码的函数。我希望这个函数返回 jQuery 语句的结果。它不起作用,我正在努力找出原因。

function showGetResult (name) {
    var scriptURL = "somefile.php?name=" + name;
    return $.get(scriptURL, {}, function(data) { return data; });
}

alert (showGetResult("John"));

The alert displays "[object XMLHttpRequest]." However, if I run the jQuery statement by itself, outside of a function, it works fine -> $.get(scriptURL, {}, function(data) { alert(data); })

警报显示“ [object XMLHttpRequest].” 但是,如果我在函数之外单独运行 jQuery 语句,它可以正常工作->$.get(scriptURL, {}, function(data) { alert(data); })

I'd like to be able to re-use this code by putting it inside of a function that returns the $.getdata. What fundamental mistake am I making here?

我希望能够通过将它放在返回$.get数据的函数中来重用此代码。我在这里犯了什么根本错误?

回答by tvanfosson

You have a few different mistakes. First, $.get doesn't return the return value of the callback function. It returns the XHR object. Second, the get function isn't synchronous, it's asynchronous so showGetResult will likely return before get completes. Third, you can't return something from inside the callback to the outer scope. You can, however, bind a variable in the outer scope and set it in the callback.

你有几个不同的错误。首先,$.get 不返回回调函数的返回值。它返回 XHR 对象。其次,get 函数不是同步的,它是异步的,因此 showGetResult 可能会在 get 完成之前返回。第三,你不能从回调内部返回一些东西到外部作用域。但是,您可以在外部作用域中绑定变量并在回调中设置它。

To get the functionality that you want, you'll need to use $.ajax and set the async option to false. Then you can define a variable in the outer scope and assign it in the ajax callback, returning this variable from the function.

要获得您想要的功能,您需要使用 $.ajax 并将 async 选项设置为 false。然后你可以在外部作用域定义一个变量并在ajax回调中赋值,从函数中返回这个变量。

function showGetResult( name )
{
     var result = null;
     var scriptUrl = "somefile.php?name=" + name;
     $.ajax({
        url: scriptUrl,
        type: 'get',
        dataType: 'html',
        async: false,
        success: function(data) {
            result = data;
        } 
     });
     return result;
}

You would probably be better served, though, figuring out how to do what you want in the callback function itself rather than changing from asynchronous to synchronous calls.

但是,您可能会得到更好的服务,弄清楚如何在回调函数本身中执行您想要的操作,而不是从异步调用更改为同步调用。

回答by Darin Dimitrov

The fundamental mistake you are making is that the AJAX call is made asynchronously, so by the time you return, the result is not yet ready. To make this work you could modify your code like this:

您犯的根本错误是 AJAX 调用是异步进行的,因此当您返回时,结果尚未准备好。为了完成这项工作,您可以像这样修改代码:

$(function() {
    showGetResult('John');
});

function showGetResult (name) {
    $.get('somefile.php', { 
        // Pass the name parameter in the data hash so that it gets properly
        // url encoded instead of concatenating it to the url.
        name: name 
    }, function(data) { 
        alert(data); 
    });
}

回答by queen3

Looks like you want synchronous request: How can I get jQuery to perform a synchronous, rather than asynchronous, Ajax request?

看起来您想要同步请求: 如何让 jQuery 执行同步而不是异步的 Ajax 请求?

Or, you may want to pass callback to your function:

或者,您可能希望将回调传递给您的函数:

function showGetResult (name, callback) {
  var scriptURL = "somefile.php?name=" + name;
  return $.get(scriptURL, {}, callback);
}

showGetResult("John", function(data){ alert(data); });

回答by Jacob Mattison

The fundamental mistake is the "asynchronous" part of AJAX. Because you don't know how long the server will take to send back a response, AJAX methods never "block" -- that is, you don't call out to the server and just sit there waiting for the result. Instead, you go on to something else, but you set up a method, called the "callback", that will fire when the results come back. This method is responsible for doing whatever needs to be done with the data (e.g. injecting it into the page).

根本的错误是 AJAX 的“异步”部分。因为您不知道服务器返回响应需要多长时间,所以 AJAX 方法永远不会“阻塞”——也就是说,您不会调用服务器而只是坐在那里等待结果。相反,您继续做其他事情,但是您设置了一个称为“回调”的方法,该方法将在结果返回时触发。这个方法负责对数据做任何需要做的事情(例如将它注入到页面中)。

回答by jatanp

This is the wrong way to do. The function(data) is a call back function so whenever return $.getwill execute .. there is possibility that call back function would have not been called.

这是错误的做法。function(data) 是一个回调函数,因此无论何时return $.get都会执行 .. 回调函数可能不会被调用。

Better you call your post data get function from function(data) method.

最好从 function(data) 方法调用你的 post data get 函数。

回答by Cosmo Arun

An efficient way is to use jQuery's Deferred method, both sync/async requests to server and wait for deferred.resolve() and then return the deferred promise object. Looks a bit tedious, but a little study is sure helpful for large data. ( tvanfosson's function works well in this case, but when I was working on google analytics data, a large amount of information made me crazy and thus i need to find this solution)

一种有效的方法是使用 jQuery 的 Deferred 方法,同步/异步请求到服务器并等待 deferred.resolve() 然后返回延迟的承诺对象。看起来有点乏味,但是稍微研究一下对于大数据肯定是有帮助的。(tvanfosson 的函数在这种情况下运行良好,但是当我在处理 google 分析数据时,大量信息让我发疯,因此我需要找到这个解决方案)

     function showResults(name) { 
        var deferred = $.Deferred, requests = [];

        requests.push($.ajax({url:"/path/to/uri/?name=" + name, type: "GET", async: false}).done(function(d) { 
         //alert or process the results as you wish 
        }));
        $.when.apply(undefined, requests).then(function() { deferred.resolve(); }); 
        return deferred.promise();

    }

the returned promise object can also be used with $.when(showResults('benjamin')).done(function() { });for post modifications (like chart/graph settings etc). totally reusable. You may also put this function in a loop of $.deferred requests like,

返回的承诺对象也可用于$.when(showResults('benjamin')).done(function() { });后期修改(如图表/图形设置等)。完全可重复使用。您也可以将此函数放入 $.deferred 请求的循环中,例如,

        function updateResults() { 
             var deferred = $.Deferred, requests = [];
             requests.push($.ajax(url:"/path/to/names/?nameArr=" + jsonArrOfNames, type: "GET", async: false}).done(function(res) {  requests.push(showResults(res[0]));}) );
             $.when.apply($, requests).then(function() { deferred.resolve(); }); 
             return deferred.promise();
            }