使用Ajax请求并接受后台数据以及数据的简单处理

 假设数据库中有这样一张表用来记录文章信息,其中picturepath是记录的文章中的图片,不同图片用;隔开

 后台返回json数据:

/**
	 * 查询所有文章
	 * 
	 * @author xuLiang
	 * @since 0.0.1
	 */
	@GetMapping("/articles")
	@ResponseStatus(HttpStatus.OK)
	@ResponseBody
	@Override
	public GetArticleResp getAllArticles() {
		GetArticleResp getArticleResp = new GetArticleResp();
		getArticleResp.setCode(1);
		getArticleResp.setMessage("查询成功");
		getArticleResp.setArticles(usersService.getAllArticles());
		return getArticleResp;
	}
public class GetArticleResp {
	private int code;
	private String message;
	private VoGetArticleResp voGetArticleResp;
	private List<Article> articles;

	public int getCode() {
		return code;
	}

	public void setCode(int code) {
		this.code = code;
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String massage) {
		this.message = massage;
	}

	public VoGetArticleResp getVoGetArticleResp() {
		return voGetArticleResp;
	}

	public void setVoGetArticleResp(VoGetArticleResp voGetArticleResp) {
		this.voGetArticleResp = voGetArticleResp;
	}

	public List<Article> getArticles() {
		return articles;
	}

	public void setArticles(List<Article> articles) {
		this.articles = articles;
	}
}

当前端收到数据后如何对json进行处理?

先新建一个页面index.html

<!DOCTYPE html> 
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml"> 
<head> <meta charset="UTF-8">
 <title>测试HTML页面</title>
 <script src="http://code.jquery.com/jquery-1.4.1.min.js"></script>
 <script src="http://code.jquery.com/jquery-1.4.1.js"></script>
 </head>
 <body> 
 <div id="myDiv"><h2>使用 AJAX 修改该文本内容</h2></div>
 <div id="myDiv2"></div>
 <div id="myDiv3"></div>
 <a>***********************************************分隔符*******************************************</a>
  <div id="myDiv4"></div>
<button onclick="LoadXmlHttp()";> 读取数据</button>
 </body> 
 </html>

 打开localhost/index后如下:

 接下来的重点就在LoadXmlHttp()方法里:

首先要用ajax发送请求,具体用法可以百度,也可以直接用postman来生成代码,这里介绍用postman来生成。

打开postman先在地址栏中输入访问的地址,注意请求方法是GET,点击send

 可以看到返回的json:

点击右上角橙色字体的Code,代码语言选择Javascript XHR,

可以看到自动生成的代码了,接下来对代码进行修改,首先在if (this.readyState == 4)里加上条件&& this.status==200,因为只有后台返回状态码为200时才意味着读取成功了,否则就是没有读取到数据

<script>
 function LoadXmlHttp(){
				var data = null;
				var xhr = new XMLHttpRequest();
				xhr.withCredentials = true;
				xhr.addEventListener("readystatechange", function () {
				  if (this.readyState == 4&& this.status==200) {					console.log(this.responseText);				 
				  }
				});
				xhr.open("GET", "http://localhost/articles");
				xhr.setRequestHeader("Content-Type", "application/json");
				xhr.setRequestHeader("cache-control", "no-cache");
				xhr.send(data);

}
</script>

然后就要对读取到的json进行进一步操作,因为此处收到的json只是一个字符串,要先用JSON.parse()函数将他转换为json对象,转换为对象后就可以直接读取里面的数据了,比如:

 var obj=JSON.parse(this.responseText);
 alert(obj.message);

完整代码:

 function LoadXmlHttp(){
				var data = null;
				var xhr = new XMLHttpRequest();
				xhr.withCredentials = true;
				xhr.addEventListener("readystatechange", function () {
				  if (this.readyState == 4&& this.status==200) {			
                            var obj=JSON.parse(this.responseText);
                                    alert(obj.message);
                                console.log(this.responseText);				 
				  }
				});
				xhr.open("GET", "http://localhost/articles");
				xhr.setRequestHeader("Content-Type", "application/json");
				xhr.setRequestHeader("cache-control", "no-cache");
				xhr.send(data);

}

这时候页面就会提示:

对于复杂json对象,需要以数组的形式来选择

var response="<h4>"+obj.articles[0].type+"</h4><h2>"+obj.articles[0].title+"</h2>"+obj.articles[0].content;

在图片路径中储存了多个图片的路径,并用;隔开了,在这里用split()方法进行分割

 var picture=obj.articles[0].picturepath;
		function ReadPic(){
		var str=picture.split(';');
		var d1=document.getElementById("myDiv2");
		var d2=document.getElementById("myDiv3");
		var img=document.createElement("img");							
		img.src=str[0];
		d1.appendChild(img);
		var img2=document.createElement("img");	
		img2.src=str[1];
	        d2.appendChild(img2);								
							}

整个script代码:

<script>
 function LoadXmlHttp(){
				var data = null;
				var xhr = new XMLHttpRequest();
				xhr.withCredentials = true;
				xhr.addEventListener("readystatechange", function () {
				  if (this.readyState === 4&& this.status==200) {			  
							 var obj=JSON.parse(this.responseText);
							 alert(obj.message);
							 var response="<h4>"+obj.articles[0].type+"</h4><h2>"+obj.articles[0].title+"</h2>"+obj.articles[0].content;
							 var picture=obj.articles[0].picturepath;
							function ReadPic(){
								var str=picture.split(';');
								var d1=document.getElementById("myDiv2");
								var d2=document.getElementById("myDiv3");
								var img=document.createElement("img");							
								img.src=str[0];
								d1.appendChild(img);
								var img2=document.createElement("img");	
								img2.src=str[1];
								d2.appendChild(img2);								
							}
							ReadPic();							
						    document.getElementById("myDiv").innerHTML=response;
							var response2="<h4>"+obj.articles[1].type+"</h4><h2>"+obj.articles[1].title+"</h2>"+obj.articles[1].content;
							document.getElementById("myDiv4").innerHTML=response2;
							console.log(this.responseText);				 
				  }
				});
				xhr.open("GET", "http://localhost/articles");
				xhr.setRequestHeader("Content-Type", "application/json");
				xhr.setRequestHeader("cache-control", "no-cache");
				xhr.send(data);

}
</script>

其中这两行代码POST请求才会用到,GET可省略

var data = null;
xhr.send(data);

现在打开页面进行测试:

点击按钮“读取数据”:

可以看到所有数据都能正常展示,还可以用CSS来进行排版美化。

 

 

 

 

 

 

 

 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值