使用 jQuery 在函数中返回 $.get 数据 [英] Return $.get data in a function using jQuery

查看:20
本文介绍了使用 jQuery 在函数中返回 $.get 数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

alert (showGetResult("John"));

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

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

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

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

推荐答案

你有几个不同的错误.首先,$.get 不返回回调函数的返回值.它返回 XHR 对象.其次,get 函数不是同步的,它是异步的,所以 showGetResult 可能会在 get 完成之前返回.第三,您不能将回调内部的某些内容返回到外部范围.但是,您可以在外部范围内绑定变量并在回调中设置它.

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.

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

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.

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.

这篇关于使用 jQuery 在函数中返回 $.get 数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆