今天在项目中遇到了一个问题,就是在定义了一个函数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;
    }

这样问题就解决了。

相关文章:

  • 2021-10-16
  • 2021-11-05
  • 2021-10-23
  • 2022-12-23
  • 2022-12-23
  • 2021-11-15
  • 2022-12-23
猜你喜欢
  • 2021-06-17
  • 2021-10-26
  • 2021-08-16
  • 2022-12-23
  • 2021-09-27
  • 2021-11-03
  • 2021-09-27
相关资源
相似解决方案