Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/396.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 从回调中触发时,函数未返回任何值_Javascript_Jquery_Json_Loops - Fatal编程技术网

Javascript 从回调中触发时,函数未返回任何值

Javascript 从回调中触发时,函数未返回任何值,javascript,jquery,json,loops,Javascript,Jquery,Json,Loops,我正在研究一个函数,它向其他jQuery回调提供数据。问题是我没法用它。 当我将fetchdata()函数的内容直接放入.click回调函数时,它可以工作,但我需要一个单独的泛型函数,以便将来可以将其用于多个不同的回调。 有人能指出我做错了什么吗?fetchdata()函数中的循环似乎中断,并且没有返回任何值 function fetchdata(){ var html; $.ajax({ url:'/test.php',

我正在研究一个函数,它向其他jQuery回调提供数据。问题是我没法用它。 当我将fetchdata()函数的内容直接放入.click回调函数时,它可以工作,但我需要一个单独的泛型函数,以便将来可以将其用于多个不同的回调。 有人能指出我做错了什么吗?fetchdata()函数中的循环似乎中断,并且没有返回任何值

    function fetchdata(){
        var html;
        $.ajax({
            url:'/test.php', 
            data:{ action: 'fetch-data' },
            dataType:'json',
            async: false,
            success: function(data){
                var entries = [];
                $.each(data, function(id, val){
                    entries.push(val.sample);
                });
                var html = entries.join('');
            }
        });
        return html;
    }
    $(document).on('click', 'a.btn.execute', function(e) {
        e.preventDefault();
        var html =  fetchdata();
        $('div#container').html(html);
    });

PS:为了上面的演示,我稍微修改了我的代码,问题应该仍然存在。

发生这种情况是因为您有
var html=entries.join(“”)在成功回调中,该回调与上一个html变量重叠。Just
html=entries.join(“”)将起作用。但是请不要真正使用
async:false
,因为它已经过时了

这里有一个更好的解决方案:

function fetchdata(callback){
    $.ajax({
        url:'/test.php', 
        data:{ action: 'fetch-data' },
        dataType:'json',
        success: function(data){
            var entries = [];
            $.each(data, function(id, val){
                entries.push(val.sample);
            });
            var html = entries.join('');
            callback(html);
        }
    });
}
$(document).on('click', 'a.btn.execute', function(e) {
    e.preventDefault();
    fetchdata(function(html){
      $('div#container').html(html);
    });
});

谢谢你,你的解决方案对我来说很好!再问一个问题;我应该怎么做才能把额外的参数传递给函数?没关系,明白了。(fetchdata('参数',函数(html){…)