ajax异步传输数据,return返回值为空

今天在项目中遇到了一个问题,就是在定义了一个函数drawHtml(),本意是想在函数运行结束后,返回拼接的字符串,可是函数运行结束后始终返回的是undefined

有BIG的代码:

function drawHtml(){
        var html ="";
        $.ajax({
            type:'get',
            url:'http://localhost:63342/projectStudy/json/data.json',
            success:function(data){
                var dataList = data.peopleList;
                for(var i=0;i<dataList.length;i++){
                   html+=`<p>姓名</p><p>${dataList[i].name}</p>
                            <p>年龄</p><p>${dataList[i].name}</p>`
                }
                console.log(html);//此处输出的html是有值的
            }
        })
        console.log(html);//返回的值为空
        return html;
    }

出现问题的原因:因为jquery的ajax是异步请求,在函数还没有执行完ajax请求时,就已经return出来了html。所以输出html是空值

解决方法:

function drawHtml(){
        var html ="";
        $.ajax({
            type:'get',
            url:'http://localhost:63342/projectStudy/json/data.json',
            async:false,//将异步的方法改为同步
            success:function(data){
                var dataList = data.peopleList;
                for(var i=0;i<dataList.length;i++){
                   html+=`<p>姓名</p><p>${dataList[i].name}</p>
                            <p>年龄</p><p>${dataList[i].name}</p>`
                }
                console.log(html);//此处输出的html是有值的
            }
        })
        console.log(html);//返回的值为空
        return html;
    }

这样问题就解决了。

猜你喜欢

转载自www.cnblogs.com/bllx/p/9038457.html