Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/68.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
Jquery在函数中返回JSON对象_Jquery - Fatal编程技术网

Jquery在函数中返回JSON对象

Jquery在函数中返回JSON对象,jquery,Jquery,我正在使用JSON进行行计数,并在我的php文件JSON_data2.php中获得如下输出: 现在我使用Javascript/Jquery函数调用这个文件,并尝试返回行。我假装这样做: function limit(keyword){ $.getJSON("json_data2.php?l="+keyword,function(data) { $.each(data.limit,function(data){

我正在使用JSON进行行计数,并在我的php文件JSON_data2.php中获得如下输出:

现在我使用Javascript/Jquery函数调用这个文件,并尝试返回行。我假装这样做:

function limit(keyword){
        $.getJSON("json_data2.php?l="+keyword,function(data)
        {
            $.each(data.limit,function(data){
                var rows = data.rows;
                return rows;
            });
        });
    }

但每次调用脚本中的函数时,都会出现未定义的情况。有指针吗?

您需要修复每条语句。添加此项是为了引用有问题的数据


函数limitkeyword不返回任何值

现有的返回运算符在回调函数中返回值$each

您必须在limit函数体中添加return运算符。

这是因为$.getJSON是异步的,因此调用limit不会返回任何有用的内容

实现这一点的方法是提供一个回调函数来限制:


在哪里可以得到未定义的?当我调用函数时,我的意思是上面哪一行返回未定义的?你有错误吗?还是与显示的内容有关?在web浏览器中转到json_data2.php?l=时会发生什么情况?@ExplosionPills OP未定义,因为limit返回它:现在我在控制台中看到127,但函数的变量仍然未定义nole显示1次127,。。。从函数和一次未定义的调用。。。还是一样的问题吗
function limit(keyword){
        $.getJSON("json_data2.php?l="+keyword,function(data)
        {
            $.each(data.limit,function(data){
                var rows = data.rows;
                return rows;
            });
        });
    }
limit(keyword, function(rows) {
    // your rows have loaded
});

  function limit(keyword, cb){
            $.getJSON("json_data2.php?l="+keyword,function(data)
            {

                $.each(data.limit,function(){
                    var rows = this.rows;
                    console.log(rows);
                    cb(rows);
                });
            });
        }
limit(keyword, function(rows) {
    // your rows have loaded
    $.each(rows, function() {
        // process each row here
    });
});

function limit(keyword, cb)
{
    $.getJSON('json_data2.php?l=' + encodeURIComponent(keyword), function(data) {
        // invoke the callback function that was passed
        cb(data.limit);
    });
}