Use Ajax Read JSON form Server.


Note : Những thứ chúng ta cần chuẩn bị bao gồm :

Project sẻ chuẩn bị như hình sau :

d1

 

 

Chúng ta có class Product.java như sau :


package thaihoanghai;
public class Product {
 private String id;
 private String name;
 private double price;
 private int unit;

 public Product(String id, String name, double price, int unit) {
 setId(id);
 setName(name);
 setPrice(price);
 setUnit(unit);
 }
 public String getId() {
 return id;
 }
 public void setId(String id) {
 this.id = id;
 }
 public String getName() {
 return name;
 }
 public void setName(String name) {
 this.name = name;
 }
 public double getPrice() {
 return price;
 }
 public void setPrice(double price) {
 this.price = price;
 }
 public int getUnit() {
 return unit;
 }
 public void setUnit(int unit) {
 this.unit = unit;
 }

}

 

Tạo ra 1 servlet ShowMobiles và tùy chỉnh trong doPost:


protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 response.setHeader("Cache-Control", "no-cache");
 response.setHeader("Prama", "no-cache");
 response.setContentType("text/javascript");

Product p1 = new Product("SP001", "Iphone 4S", 8000, 2);
 Product p2 = new Product("SP002", "Iphone 5", 10000, 3);
 Product p3 = new Product("SP003", "Galaxy 4", 7000, 4);
 Product p4 = new Product("SP004", "Galaxy 5", 15000, 5);
 List<Product> listP = new ArrayList<Product>();
 String param = request.getParameter("mobileType");
 if(param.equalsIgnoreCase("apple")){
 listP.add(p1);
 listP.add(p2);
 }else if(param.equalsIgnoreCase("samsung")){
 listP.add(p3);
 listP.add(p4);
 }else{
 listP.add(p1);
 listP.add(p2);
 listP.add(p3);
 listP.add(p4);
 }
 JSONArray listPJSON = new JSONArray(listP,false);
 PrintWriter out = response.getWriter();
 out.print(listPJSON);

}

OK zậy là ta đả thiệt lập cho data Server trả về là 1 chuổi JSON

Tiếp đến chúng ta chuẩn bị thiệt lập Ajax code cho việc thao tác đến server và nhận data về.

page ajax-utils.js như sau :

function getRequestObject() {
 if (window.ActiveXObject) {
 return(new ActiveXObject("Microsoft.XMLHTTP"));
 } else if (window.XMLHttpRequest) {
 return(new XMLHttpRequest());
 } else {
 return(null);
 }
}

&nbsp;

function htmlInsert(id, htmlData) {
 document.getElementById(id).innerHTML = htmlData;
}
function getValue(id) {
 return(escape(document.getElementById(id).value));
}

&nbsp;

function ajaxPost(address, data, responseHandler) {
 var request = getRequestObject();
 request.onreadystatechange =
 function() { responseHandler(request); };
 request.open("POST", address, true);
 request.setRequestHeader("Content-Type",
 "application/x-www-form-urlencoded");
 request.send(data);
}

 

Thiết lập lênh chạy cho client đến server

page json_generate_example.js


function showTable1(address, inputField, resultRegion){
 var data = "mobileType=" + getValue(inputField); // get input form user
 ajaxPost(address, data, function(request){
 showMobileInfo1(request,resultRegion); // innerHTML into resultRegion
 });
}

function showMobileInfo1(request,resultRegion){
 if((request.readyState==4) && (request.status==200)){
 var rawData = request.responseText;
 var data = eval("(" + rawData + ")");
 var headings = ["ID","NAME","PRICE","UNIT"];
 var rows = new Array();
 for(var i = 0 ; i<data.length; i++){
 var mobile = data[i];
 rows[i] = [mobile.id, mobile.name, mobile.price, mobile.unit];
 }

 var table = getTable(headings, rows);
 htmlInsert(resultRegion, table);

 }
}

OK ta tạo ra 1 trang index.jsp như sau :

<%@ page language=”java” contentType=”text/html; charset=ISO-8859-1″
pageEncoding=”ISO-8859-1″%>
<!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN” “http://www.w3.org/TR/html4/loose.dtd”&gt;
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=ISO-8859-1″>
<title>Introduce JSON</title>
<script src=”./scripts/ajax-utils.js” type=”text/javascript”></script>
<script src=”./scripts/json-generation-examples.js”
type=”text/javascript”></script>
<script src=”./scripts/json2.js” type=”text/javascript”></script>
</head>
<body>

<table border=”5″>
<tr><th class=”title”>Generate JSON from Java Object</th></tr>
</table>
<p/>
<fieldset>
<legend>MVC</legend>
<form action=”#”>
<label for=”type”>Product Type:</label>
<select id=”type”>
<option value=”null”>[-Choose Product-]</option>
<option value=”apple”>Product’s Nokia</option>
<option value=”samsung”>Product’s SamSung</option>
</select>
<br/>
<input type=”button” value=”Show Products”
onclick=’showTable1(“ShowMobiles”, “type”, “table1″)’/>
</form>
<p/>
<div id=”table1”></div>
</fieldset>
<p/>
</body>
</html>

[/cdoe]

 

Kết quả của bài sau khi nhấn button : Show Product :

 

aa

 

Source code : http://www.mediafire.com/?39l4zjw44xcbjt1

Posted in Ajax. 1 Comment »

One Response to “Use Ajax Read JSON form Server.”


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: