Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/87.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 jQuery将一直等待,直到获取数据_Javascript_Jquery_Ajax - Fatal编程技术网

Javascript jQuery将一直等待,直到获取数据

Javascript jQuery将一直等待,直到获取数据,javascript,jquery,ajax,Javascript,Jquery,Ajax,我的代码中有一个javascript函数,它使用ajax post请求从服务器获取数据 function fetchData(keyword) { $.post( 'http://example.com/apiv5/ajax/', { command: 'fetchxxx', token: 'xxxyyyzzz', data: keyword }, fu

我的代码中有一个javascript函数,它使用ajax post请求从服务器获取数据

function fetchData(keyword)
{
    $.post(
        'http://example.com/apiv5/ajax/',
        {
            command: 'fetchxxx',
            token: 'xxxyyyzzz',
            data: keyword
        },
        function(data)
        {
            return data;
        }
    );
}
我需要将数据连接成这样的变量,在这里我实际调用函数

var msg = '<p class="question">'+thisGuy.data('description')+'</p>'+fetchData(thisGuy.data('title'));
var msg='

'+thisgue.data('description')+'

'+fetchData(thisgue.data('title'));
注意这里
thisgouy=$(this)

现在的问题是,
fetchData()
函数需要几秒钟来获取和加载数据,但与此同时,javascript会跳过这个过程,并将一个“未定义”放在函数的返回值上。


现在,我如何告诉他们等待,直到它获取数据,一旦完成,然后将数据连接到该变量中?我见过wait()方法,但不知道如何使用它。

将fetchData转换为承诺,并在Ajax查询的回调中解决它。

您应该理解,对于任何异步调用,都不能从函数返回任何内容。您唯一能做的就是等待请求完成并访问回调中的响应

由于
jQuery.post
方法返回一个jqXHR对象,该对象派生自延迟对象,因此我们可以使用.done()方法附加一个成功回调。请看这里的文档

试试这样的

function showMsg () {
    var thisGuy = $(this);

    fetchData(thisGuy.data('title'))
   .done(function (data) {
       var msg = '<p class="question">'+thisGuy.data('description')+'</p>'+data);
       //Now you can use the msg 
    });
}

function fetchData(keyword)
{
    return $.post('http://example.com/apiv5/ajax/',
        {
            command: 'fetchxxx',
            token: 'xxxyyyzzz',
            data: keyword
        });
}
函数showMsg(){
var thisgue=$(this);
fetchData(thisguiy.data('title'))
.完成(功能(数据){
var msg='

'+thisgue.data('description')+'

'+data); //现在你可以用味精了 }); } 函数fetchData(关键字) { 返回$.post('http://example.com/apiv5/ajax/', { 命令:“fetchxxx”, 标记:“xxxyyzzz”, 数据:关键字 }); }