vue.js框架+mintUI 网站自建之讨厌的BUG:$.ajax 拿不到后台发过来的数据

版权声明:转载请标注出处与作者,写文不易,相互尊重从小事做起。 https://blog.csdn.net/JasonRaySHD/article/details/89185349

原本想从后台拿到图片数据加载到img标签src中,结果发现明明ajax请求数据成功了,但是src一直为空,无法将数据赋值到src中。

最初 在methods中提交ajax请求代码如下:

		getimage(){
         var  _this = this;
		$.ajax({
                type:'get',
                url:'./test2.php',
                success(response) {
                    response = JSON.parse(response);
                    if (response.code == "200") {
                      console.log(response);
                      _this.imagedata=response.data.imagedata;
                    }else{
                        console.log("fail to upload");
                    }
                },
                error(err){
                    console.log("an error occurred");
                }
            });
            document.getElementById('image').src=this.imagedata;
		},

BUG原因以及解决方法:
ajax为异步执行的(关于ajax原理见https://www.cnblogs.com/wanghp/p/6991554.html),所以在执行document.getElementById时很有可能imagedata并没有被赋值。
解决方法如下:

		getimage(){
         var  _this = this;
		$.ajax({
                type:'get',
                url:'./test2.php',
                success(response) {
                    response = JSON.parse(response);
                    if (response.code == "200") {
                      console.log(response);
                      _this.imagedata=response.data.imagedata;
                    }else{
                        console.log("fail to upload");
                    }
                },
                error(err){
                    console.log("an error occurred");
                }
            });
		}
		
//在html中加入v-for,当赋值成功后,让浏览器自动加载出所有图片,不再手动绑定src
<img v-for='item in imagedata' :src='item'/>


哦 对了,之前我直接写的_this=this,没有显示定义this为变量(var _this = this),导致拿到的结果是:
在这里插入图片描述
并不是图片的base64编码,而是Getter & Setter 这种,但好像不影响最终图片显示的结果。
这里也可以在ajax命令中加入: async:false 取消异步加载。但是一般会被浏览器忽略

猜你喜欢

转载自blog.csdn.net/JasonRaySHD/article/details/89185349