代码之家  ›  专栏  ›  技术社区  ›  Xavier

在Javascript函数内编写jQuery不起作用

  •  0
  • Xavier  · 技术社区  · 8 年前

    我有一个js文件叫做 example.js 其线条如下:

    gridOptions.api.setRowData(createRowData());
    

    然后还有另一个文件 data.js 哪个有 createRowData() 应返回的函数 ROW_DATA . 具体如下:

    function createRowData() {
        jQuery.getJSON('/file.txt',function(ROW_DATA){
    
        return ROW_DATA;
    
        });
    
    }
    

    但是,无论何时 createRowData() 实例js公司 文件,它不会进入 jQuery 块并简单地转到最后一个花括号。谁能告诉我这里出了什么问题??

    2 回复  |  直到 8 年前
        1
  •  2
  •   Dream_Cap    8 年前

    我相信你没有得到这个值,因为getJSON是异步的,正如其他人所说的那样。createRowData是在稍后而不是在调用时检索值。

    这是一种通过承诺获取数据的方法。我评论了下面发生的事情:

    function createRowData() {
        //return a new promise
        return new Promise(function(resolve, reject){
    
        jQuery.getJSON('/file.txt',function(ROW_DATA){
         //on reject, send an error
         if (ROW_DATA === null) reject("Error fetching data");
        //on resolve, send the row data
        return resolve(ROW_DATA);
    
        });
    });
    }
    //use then to describe what happens after the ajax request is done
    gridOptions.api.setRowData(createRowData()).then(function(rowdata){
    return rowdata; //log data or error
    })
    

    编辑:要执行一个同步ajax请求,您可以这样做,参考以下内容 SO question .

    function createRowData() {
    
        $.ajax({
        url: "/file.txt'",
        async: false,
        success: function(rowdata){
        return rowdata
        }
    })
    
    }
    

    要将一些数据读取到您提到的变量中,nodejs可能会有所帮助,因为它可以处理读取输入/输出,也可能处理读取到变量的操作:

        2
  •  2
  •   kkica    7 年前

    从文件中获取JSON,将结果传递给回调函数,然后返回。返回到哪里??

    回调

    程序说:当你从文件中读取完毕后,调用这个函数,好吗?。

    这就是它所做的。程序将继续运行,直到文件被读取,这时将调用回调匿名函数。 你可以做这样的事。

    createRowData(gridOptions.api);
    // add code here if you want this code to execute even before you get the response
    function createRowData(api) {
        jQuery.getJSON('/file.txt',function(ROW_DATA,api){   
        api.setRowData(ROW_DATA);   
        //Whatever else you want to do. In case you want this to be done only 
        //after the values have been read
        });
    }
    

    如果您想等待文件被读取,只需在函数之后不做任何事情,而是将其放入回调函数中。