Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 将jQueryAjax请求的结果返回给变量,而不是触发函数_Javascript_Jquery - Fatal编程技术网

Javascript 将jQueryAjax请求的结果返回给变量,而不是触发函数

Javascript 将jQueryAjax请求的结果返回给变量,而不是触发函数,javascript,jquery,Javascript,Jquery,我正在使用jquery测试MCV。我正在调用一个api,它返回数据——我想做的是将数据返回到一个变量,而不是在我的模型中调用一个additioall函数。尽管(The_data=result),但下面的代码并没有实现我希望的功能。有什么办法可以做到这一点吗 function lookForSomething() { var the_data = $.ajax({ type: "GET", url: TheUrl,

我正在使用jquery测试MCV。我正在调用一个api,它返回数据——我想做的是将数据返回到一个变量,而不是在我的模型中调用一个additioall函数。尽管(The_data=result),但下面的代码并没有实现我希望的功能。有什么办法可以做到这一点吗

function lookForSomething()
{
    var the_data = $.ajax({ type: "GET", 
                            url: TheUrl, 
                            dataType: "jsonp", 
                            success: function(result) { return result; } 
                            });
    return the_data;
}
非常感谢,,
J

如果您理解正确,您希望URL返回的数据是lookForSomething的返回值

从技术上讲,您可以使用async选项执行此操作:

function lookForSomething()
{
    var the_data;
    $.ajax({ type: "GET", 
                            url: TheUrl, 
                            dataType: "jsonp", 
                            async : false,
                            success: function(result) { the_data = result; } 
                            });
    return the_data;
}

我强烈要求你不要这样做。它不像Javascript,在运行时会锁定用户的浏览器。最好将回调传递给函数,并从您可能正在寻找的
success
调用它:


请记住,这仍然是异步的,因此当您调用
var ddd=lookForSomething()时,ddd将不会具有您期望的值,因为调用可能仍在运行。我提出
$.when()
的唯一原因是,您似乎需要很多依赖项<代码>$。when()
允许您等待。

您是在访问服务器还是在实际使用jsonp调用?我使用它来查询google books api,但在不使用jsonp时遇到了一个错误。感谢您的回答-我很高兴学习一种更类似javascript的MVC方法,但这很棘手。本质上,我希望控制器从这个函数请求数据,然后将数据发送到“视图”函数,该函数将返回的数据写入浏览器。添加从success调用函数会使“模型”的行为更像控制器……如果控制器向模型传递回调,并且该回调(是控制器的一部分,尽管是由模型调用的回调)将数据发送到视图,这种安排能满足您对MVC应该如何运行的审美要求吗?谢谢这个-when()方法对我来说是新的-我会检查它的。+1为您提供了出色的
$。when
函数-因为暗示这会解决OP的问题。回拨中的回报毫无用处。@Malvolio:是的,我想你是对的。这个功能仍然是相当无用的;它应该有一个callbackfunction作为参数。
function lookForSomething()
{
    var the_data;
    $.when(
        $.ajax({ type: "GET", 
                            url: TheUrl, 
                            dataType: "jsonp", 
                            success: function(result) { the_data=result; } 
                            });
    ).done(function() {
        return the_data;
    }).fail(function() {
        return '';
    });
}