猿问

js ajax 请求问题。

在项目中,通过 ajax 请求后台数据,并做数据处理。最后将处理好的数据返回。代码形式如下:


function funOne(){

    var htmlStr = '';

    $.get(href,{},function(r){

        var data = eval('(' + r + ')');

        $.each(data,function(k,v){

            /*    在该区域做相应的数据处理 */

            htmlStr += '<div>' + v + '</div>';

        })

    })

    return htmlStr;

}

以上是代码的逻辑。问题出现在,ajax 请求内部的运算还没结束,已经返回了结果,所以函数调用的结果是空的。

该问题如何解决?尝试过用 while ,但是直接太多蹦掉了。


明月笑刀无情
浏览 476回答 3
3回答

宝慕林4294392

function funOne() {&nbsp; &nbsp; var htmlStr = '';&nbsp; &nbsp; return $.get(href, {}).then(function (r) {&nbsp; &nbsp; &nbsp; &nbsp; var data = eval('(' + r + ')');&nbsp; &nbsp; &nbsp; &nbsp; $.each(data, function (k, v) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; /*&nbsp; &nbsp; 在该区域做相应的数据处理 */&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; htmlStr += '<div>' + v + '</div>';&nbsp; &nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; &nbsp; &nbsp; return htmlStr;&nbsp; &nbsp; })}funOne().then(function(htmlStr){&nbsp; &nbsp; console.log(htmlStr)})

jeck猫

写一写&nbsp;var getData = new Promise(function (resolve, reject) {&nbsp; &nbsp; &nbsp; $.get(href, {}).then(function (r) {&nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; if (r) {&nbsp; &nbsp; &nbsp; &nbsp; var data = JSON.parse(r);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; resolve(data);&nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; reject(err);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; })&nbsp; &nbsp; getData.then(function (data) {&nbsp; &nbsp; &nbsp; // 处理data&nbsp; &nbsp; }).catch((err)=>{console.log(err})
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答