ajax|js| data
Ajax HACKS-HACK7 receive JSON-formatted data
How can I use Ajax to receive JS object data from the server? You can receive data using a format called JavaScript Object notation. This hack describes user input information and gets the response data from the server in JSON format.
JSON is common and intuitive, which is probably why many developers like to use it. As an example, the server program gets the information from the server and returns it to the Web page in JSON format. The data in JSON format is described as follows:
Left Curly brace "{"
One or more property names, the corresponding values separated by colons, and the property/value pairs separated by commas.
Right curly brace "}"
The value of each property can be:
A simple string, such as "Hello"
arrays, such as [1,2,3,4]
Digital
True, FALSE, or null
Other objects, grouped, or objects in the object.
For more information, please visit: http://www.json.org
In JavaScript, the format of an object is strict. As an example, the request information in Hack2 is rewritten to the JSON format:
{
FirstName: "Bruce",
LastName: "Perry",
Gender: "M",
Country: "USA"
}
Magic JSON
In this section, we also use the example in Hack2, just processing the data in JSON format. The HTML code for the page is as follows:
"Http://www.w3.org/tr/1999/rec-html401–19991224/strict.dtd" >
A Few Facts About yourself ...
Javascript:void%200>
The name:
Last Name:
Gender:
Country of Origin:
Send Data
The script tag introduces the JS file as Hack5.js. JS sends the user input value to the server; These have been introduced in Hack2 and so on, which is not explained in detail here.
When JS handles the return value, it needs to be aware of XSS attacks. This is a potential threat for those using eval or other related functions.
As a corresponding measure, the client code can filter and detect the return value (that is, by checking the XMLHttpRequest ResponseText property) before the function eval uses responsetext
Here's the code for hack, and we'll focus on the code that handles the return value section:
var request;
var querystring; Save posted data
function SendData () {
Setquerystring ();
Url= "Http://www.parkerriver.com/s/json";
HttpRequest ("POST", url,true);
}
Event handler for XMLHttpRequest
function Handlejson () {
if (request.readystate = = 4) {
if (Request.status = = 200) {
var resp = Request.responsetext;
var func = new Function ("return" +RESP);
var OBJT = func ();
var div = document.getElementById ("JSON";
Stylizediv (RESP,DIV);
div = document.getElementById ("props";
Div.innerhtml= "
In object form ...
"+
”
Properties
Firstname= "+
Objt.firstname "
Lastname= "
Objt.lastname+ "
Gender= "+
Objt.gender+ "
Country= "+
Objt.country;
} else {
Alert ("A problem occurred with communicating between" +
"The XMLHttpRequest object and the server program."
}
}//end outer IF
}
/* Initialize A Request object is already constructed * *
function Initreq (reqtype,url,bool) {
/* Specify the function that would handle the HTTP response * *
Request.onreadystatechange=handlejson;
Request.open (Reqtype,url,bool);
Request.setrequestheader ("Content-type",
"Application/x-www-form-urlencoded; Charset=utf-8 ";
Request.send (querystring);
}
/* Wrapper function for constructing a request object.
Parameters:
Reqtype:the HTTP request type, such as Get or POST.
Url:the URL of the server program.
Asynch:whether to send the request asynchronously or not. */
function HttpRequest (reqtype,url,asynch) {
Snipped ... Hack #1 or #2
}
function setquerystring () {
Querystring= "";
var frm = document.forms[0];
var numberelements = frm.elements.length;
for (var i = 0; i < numberelements; i++) {
if (I < numberElements-1) {
QueryString = Frm.elements[i].name "=" +
encodeURIComponent (Frm.elements[i].value) + "&";
} else {
QueryString = Frm.elements[i].name "=" +
encodeURIComponent (Frm.elements[i].value);
}
}
}
function Stylizediv (bdytxt,div) {
Reset DIV Content
Div.innerhtml= "";
Div.style.fontsize= "1.2em";
Div.style.backgroundcolor= "Yellow";
Div.appendchild (document.createTextNode (bdytxt));
}
As described in hack earlier in this chapter, the Initreq () function initializes the request object and sends an HTTP request to the server.
The event handler function invokes the Handlejson. The format of the corresponding data is a JSON-formatted string, not another XML or other format of data. JS regards these return text as a string object. Therefore, the code initiates the open step before the server return value is converted to a JS object. (BTW, in this section, the server reformat the request parameter in JSON format before sending the response data.) )
No specific error handling code is included here, and it is introduced in HACK8.
In the code inside the function Handlejson (the highlighted part), the Variable RESP saves the HTTP response text, and JS sees it as a string. Interesting is the constructor of the function:
var func = new Function ("return" +RESP);
The code above will create a new function object named after the variable func. JavaScript programmers should understand that most functions need to be predefined and declared in code, or created as a function literal. In this case, however, we need to use a string to dynamically define a function body, and the constructor of the function can provide the perfect tool.
The to this site is guidance on this code usage:http://www.jibbering.com/2002/4/httprequest.html.
Another way to convert a JSON string is to:
var resp = Request.responsetext;var obj = eval ("resp") ");
When you use eval and an array, you do not have to use parentheses:
var resp = Request.responsetext;//resp saved as "[1,2,3,4]"
var arrobject = eval (resp);
The next line is used to create a thermometer that returns the literal amount of an object to describe the server return value. You can then call the function and use the return object to programmatically display the server's return results on a Web page using DOM programming.
var OBJT = func ();
var div = document.getElementById ("JSON";
Stylizediv (RESP,DIV);
div = document.getElementById ("props";
Div.innerhtml= "
In object form ...
Properties
Firstname= "+
Objt.firstname "
Lastname= "
Objt.lastname+ "
Gender= "+
Objt.gender+ "
Country= "+
Objt.country;
OBJT variables to store object literals. Variables can be obtained from the object, in the form of objt.firstname.
Figure 1-10 shows what the Web page looks like after it has received a response.
Figure 1-10. Visualizing JavaScript Properties is sweet!
On the server side
The Java servlet is used to process requests. As a more understanding of the server side, here is the code for the Dopost method of the servlet:
protected void DoPost (HttpServletRequest httpservletrequest,
HttpServletResponse HttpServletResponse) throws
Servletexception, IOException {
Map ValMap = Httpservletrequest.getparametermap ();
StringBuffer BODY = new StringBuffer ("{\\n";
if (ValMap!= null) {
String Val=null;
String key = null;
Map.entry me = null;
Set entries = Valmap.entryset ();
int size = Entries.size ();
int counter=0;
For (iterator iter= entries.iterator (); Iter.hasnext () {
counter++;
Me= (Map.entry) iter.next ();
Val= ((string[]) me.getvalue ()) [0];
Key = (String) me.getkey ();
if (counter < size) {
Body.append (Key). Append (": \ \" ". Append (val). Append (" \ ", \\n);
} else {
Remove comma for last entry
Body.append (Key). Append (": \ \" ". Append (val). Append (" \ \\n ";
}
}
}
Body.append ("}";
Ajaxutil.sendtext (Httpservletresponse,body.tostring ());
}
The Ajaxutil class sends an HTTP response to Content-type of Text/plain; Charset=utf-8 's head. Some websites also have discussions using Content-type, but, here, there is no fixed format.
The Ajaxutil class sets the header format for HTTP responses:
Response.setheader ("Cache-control", "No-cache");
<