The previous chapter describes how to use JSON to represent data. This chapter describes how to generate JSON-format data on the server to send data to the client, and how the client uses JavaScript to process data in JSON format.
We will first discuss how to use JavaScript to process JSON data on the web page. We can see how the client expresses JSON data to users through a simple JavaScript method:
Function handlejson () {var J = {"name": "Michael", "Address": {"city": "Beijing", "street": "Chaoyang Road ", "postcode": 100025 }}; document. write (J. name); document. write (J. address. city );}
Assume that the JSON data returned by the server is as follows:
{"Name": "Michael", "Address ":
{& Quot; City & quot;: & quot; Beijing & quot;, & quot; Street & quot;: & quot; Chaoyang Road & quot;, & quot; postcode & quot;: 100025}
}
You only need to assign a value to a javascript variable to use the variable immediately and update the information on the page. JSON is easy to use than XML to read various nodes from the Dom, all we need to do is to send an Ajax request and assign the JSON data returned by the server to a variable. Many Ajax frameworks already contain the ability to process JSON data,
For example, prototype (a popular JavaScript Library: http: // prototypejs.org) provides the evaljson () method, which can directly convert the JSON text returned by the server into a javascript variable:
New Ajax. Request (http: // URL ,{
Method: "Get ",
Ousuccess: function (Transport ){
VaR JSON = transport. responsetext. evaljson ();
// Todo: Document. Write (JSON. XXX );
}
);