Using JSON in Ajax

Source: Internet
Author: User
Tags object json return string tostring stringbuffer
AJAX|JS submit data using JSON instead of XML

Page: jsonexample.jsp

<%@ page contenttype= "text/html; CHARSET=GBK "%>
<title>
JSON sample
</title>
<script type= "Text/javascript" src= "Zxml.src.js" ></script>
<script type= "Text/javascript" src= "Json.js" ></script>
<script type= "Text/javascript" >
var xmlHttp;

Creating objects
function Createxmlhttprequest () {
XmlHttp = Zxmlhttp.createrequest ();
}

function Dojson () {
Get Car Object
var car = Getcarobject ();

String a car object with JSON
var Carasjson = car.tojsonstring ();
Alert ("Auto object json to: \ n" + Carasjson);

var url = "jsonexample?timestamp=" + New Date (). GetTime ();

Creating objects
Createxmlhttprequest ();
Xmlhttp.open ("POST", url,true);
Xmlhttp.onreadystatechange = Handlestatechange;
Xmlhttp.setrequestheader ("Content-type", "application/x-www-form.urlencoded");
Xmlhttp.send (Carasjson);
}

callback method
function Handlestatechange () {
if (xmlhttp.readystate = = 4) {
if (Xmlhttp.status = = 200) {
Parseresults ();
}
}
}

Parse results
function Parseresults () {
var responsediv = document.getElementById ("Serverresponse");
if (Responsediv.haschildnodes ()) {
Responsediv.removechild (Responsediv.childnode[0]);
}

var responsetext = document.createTextNode (Xmlhttp.responsetext);
Responsediv.appendchild (ResponseText);
}

Get Car Object
function Getcarobject () {
Return to New car ("Dodge", "Coronet R/t", 1968, "Yellow");
}


Car constructor
function car (make,model,year,color) {
This.make = make;
This.model = model;
This.year = year;
This.color = color;
}
</script>
<body>
<br/><br/>
<form action= "#" >
<input type= "button" value= "Send json data"/>
</form>
Server response:
<div id= "Serverresponse" >
</div>
</body>

Server: Jsonexample.java

Package AJAXBOOK.CHAP4;

Import java.io.*;
Import java.net.*;
Import java.text.ParseException;
Import javax.servlet.*;
Import javax.servlet.http.*;
Import Org.json.JSONObject;

public class Jsonexample
Extends HttpServlet {
Handling Post Methods
protected void DoPost (HttpServletRequest request,
HttpServletResponse response) throws Servletexception,
IOException {
String JSON = readjsonstringfromrequestbody (request);

Using JSON to bind a word to an Ajax object
Jsonobject jsonobject = null;
try {
Jsonobject = new Jsonobject (JSON);
}
catch (ParseException PE) {
System.out.println ("parseexception:" + pe.tostring ());
}

Return output results
String responsetext = "You have a" + Jsonobject.getint ("year") + ""
+ jsonobject.getstring ("make") + "" + jsonobject.getstring ("model")
+ "" + "that's" + jsonobject.getstring ("color") + "in color."

Response.setcontenttype ("Text/xml");
Response.getwriter (). print (responsetext);
}

Get the parameters
Private String Readjsonstringfromrequestbody (HttpServletRequest request) {
StringBuffer json = new StringBuffer ();
String line = null;
try {
BufferedReader reader = Request.getreader ();
while (line = Reader.readline ())!= null) {
Json.append (line);
}
}
catch (Exception e) {
System.out.println ("Error reading JSON string:" + e.tostring ());
}
return json.tostring ();
}
}

Note: To introduce json.js and JSON source files, use Json.jar, source files See book source code Chapter III



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.