使用ajax接收後臺傳送過來的json資料
阿新 • • 發佈:2018-12-26
今天給大家帶來一個簡單的使用ajax接收後臺返回json格式的demo
廢話不多說直接上程式碼
後臺程式碼
Pserson類package com.sidan.outjson; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.sidan.jsonutil.GetJson; /** * Servlet implementation class OutJson */ @WebServlet("/OutJson") public class OutJson extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public OutJson() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); String s = GetJson.getJson(); out.print(s); } }
package com.sidan.jsonutil; public class Person { private String name; private String sex; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
將資料包裝成json格式類(資料直接是迴圈新增的所以一樣這裡是為了簡單)
jsp頁面程式碼package com.sidan.jsonutil; import java.util.ArrayList; public class GetJson { public static String getJson(){ return json().toString(); } public static StringBuffer json(){ StringBuffer sb = new StringBuffer(); ArrayList<Person> arr = initArray(); int x = 0; sb.append("["); for(Person p:arr){ sb.append("{"); sb.append("\"name\""); sb.append(":"); sb.append("\""+p.getName()+"\""); sb.append(","); sb.append("\"age\""); sb.append(":"); sb.append("\""+p.getAge()+"\""); sb.append(","); sb.append("\"sex\""); sb.append(":"); sb.append("\""+p.getSex()+"\""); sb.append("}"); if(x != arr.size()-1){ sb.append(","); } x++; } sb.append("]"); return sb; } public static ArrayList<Person> initArray(){ ArrayList<Person> arr = new ArrayList<Person>(); for(int i = 0;i < 10;i++){ Person p = new Person(); p.setName("sdchen"); p.setAge(20); p.setSex("man"); arr.add(p); } return arr; } }
<pre name="code" class="html"><%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script src="jQuery/jquery-3.1.1.min.js"></script>
<script type="text/javascript">
$(function(){
$("#btn").click(function(){
var url = "OutJson";
$.ajax({
url:url,
type:"post",
dataType:"json",
error:function(XMLHttpRequest, textStatus, errorThrown){
alert(XMLHttpRequest);
alert(textStatus);
alert(errorThrown);
},
success:function(data){
$.each(data,function(idx,obj){
var li = document.createElement("li");
li.innerHTML = "<a>" + obj.name + "</a>";
document.getElementById("ul1").appendChild(li);
});
}
});
});
});
</script>
</head>
<body>
<ul id="ul1"></ul>
<input type="button" value="迴圈" id="btn"/>
</body>
</html>
寫這個demo也費了很大勁,畢竟是新手,也從錯誤中學到了很多,比如dataType寫成datatype時ajax預設接收的資料是為text這樣導致我總是迴圈不了,還有就是json資料的格式是非常嚴謹的
就因為最後多了一個逗號就導致總是出錯,並且迴圈不了,最後將錯誤打印出來才知道這個格式是錯了的