ajax请求拿到多条数据拼接显示在页面中

首先我们拿到的了一坨Json数据

如下

 

然后通过ajax请求拿到数据

在ajax的success方法中处理和使用数据:

其中包括:

用eval处理这种数据

var outStr = eval('('+data.data+')');

用循环取出数据并使用

$.each(outStr,function(index){
console.log(outStr[index].username);
}

综上代码:

componentDidMount (){
var _this =this;
$.ajax({
async:false,
type:"POST",
url:"http://localhost:1111/api/Users/all",
dataType:"Json",
data:{
"username":"",
},
success:function(data){
console.log("调用成功");
console.log(data.statusCode);
//拿到数据后用eval函数处理
var outStr = eval('('+data.data+')');
//循环取出数据,并拼接 $.each(outStr,
function(index){ var sexStr = "";
//数据库中的数据1是男 0是女 outStr[index].sex
== 1?sexStr = "Male":sexStr = "FeMale"; if(outStr[index].username!=localStorage.getItem("username")){ //需要拼接的内容 var htmlStr = '<div class = "userM_info">'; htmlStr += ' <div class = "userM_infoBox">'+outStr[index].name+'</div>'; htmlStr += ' <div class = "userM_infoBox">'+sexStr+'</div>'; htmlStr += ' <div class = "userM_infoBox">'+outStr[index].phoneNum+'</div>'; htmlStr += ' <div class = "userM_infoBox">'+outStr[index].address+'</div>'; htmlStr += ' <div class = "userM_fork"></div>'; htmlStr += ' </div>'; //拼接到需要的div中 $('.userM_content_data').append(htmlStr); } }) }, error:function(err){ } });
}

 最后我的页面中能显示

 

原文地址:https://www.cnblogs.com/RikuBlog/p/9530753.html