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

查看:323
本文介绍了使用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天全站免登陆