Ajax-use JSON to send data to the server

Source: Internet
Author: User
Send data to the server using JSON

After doing so much, you can use JavaScript more easily. Maybe you are considering putting more model information on the browser. However, after reading the previous example (using XML to send a complex data structure to the server), you may change your mind. It is not good to create XML strings by concatenating connections. This is not a robust technique for generating or modifying XML data structures. An alternative to JSON overview XML is JSON, which can be found at www.json.org. JSON is a text format that is independent of a specific language, but uses a convention similar to C series languages (such as C, C #, JavaScript, and so on. JSON is based on the following two data structures. Currently, almost all programming languages support these two data structures: l name/value pair sets. In the current programming language, this is implemented as an object, record, or dictionary. L value ordered table, which is usually implemented as an array. Because these structures are supported by so many programming languages, JSON is an ideal choice and can be used as a data interchange format between heterogeneous systems. In addition, JSON is based on a subset of standard JavaScript, so it should be compatible with all current web browsers. JSON objects are unordered sets of name/value pairs. The object starts with {and ends with}. Name/value pairs are separated by colons. A json array is an ordered value set ending with [start, end with]. Values in the array are separated by commas. The value can be a string (caused by double quotation marks), a value, true or false, an object, or an array. Therefore, the structure can be nested. Figure 3-6 graphically describes the markup of a json object. Figure 3-6  For graphical representation of the JSON object structure (from www.json.org), consider a simple example of the employee object. The employee object may contain data such as name, last name, employee number, and position. JSON can be used as follows to indicate the instance of the employee object: var Employee = {"firstname": John, "lastname": Doe, "employeenumber": 123, "title ": "accountant"} You can then use the standard vertex notation to use the object attributes, as shown below: var lastname = employee. lastname; // access the last namevar Title = employee. title; // access the titleemployee. employeenumber = 456; // change the employee numberjson is a lightweight data interchange format. If you use XML to describe the same employee object, it may be as follows: <employee> <firstname> JOHN </firstname> <lastname> Doe </lastname> <employeenumber> 123 </employeenumber> <title> accountant </title> </employee> apparently, JSON encoding is shorter than XML encoding. JSON encoding is relatively small, so if a large amount of data is sent on the network, it may bring significant performance differences. The www.json.org website lists at least 14 types of bindings with other programming languages. This shows that no matter what technology is used on the server side, it can communicate with the browser through JSON. JSON example (this example requires JSON. JS, http://www.json.org/js.html at the bottom of the link to download, this example uses older versions of JSON. JS. If you download a new one, the method is different. jsonobject. java, jsonarray. java, http://www.json.org/java/index.html download, which is not Java JSON-lib although there are also these two classes, may be the reason for the version is different if you want to use JSON-lib, then you must download the json-lib-2.0-jdk15.jar, but also the following five jar

Jakarta commons-Lang, Jakarta commons-beanutils, Jakarta commons-collections

Jakarta commons-logging and ezmorph cannot be missing any one. I tried --!!

The first four are downloaded at apache.org, and the last one is at http://ezmorph.sourceforge.net /.

The red font below is a different part. It depends on what you are using. I have tested it.

The following is a simple example. It shows how to use JSON to convert a javascript object to a string format, send the string to the server using Ajax technology, and then the server creates an object based on the string. In this example, there is no business logic or user interaction. It emphasizes the JSON technology on the client and server. Figure 3-7 shows a "stringized" Car object. Figure 3-7  Because this example is almost identical to the previous post example, we only focus on JSON-specific technologies. Click the button on the form to call the dojson function. This function first calls the getcarobject function to return a new car object instance, and then converts the car object to a JSON string using the JSON JavaScript Library (available for free from www.json.org, then display this string in the warning box. Next, use the XMLHTTPRequest object to send the car object encoded in JSON to the server. Because there is a JSON-Java binding library available for free, it is quite simple to compile a java servlet to provide services for JSON requests. Even better, because each server-side technology has a corresponding JSON binding, you can use any server-side technology to implement this example. Figure 3-8 Server Response after reading the JSON string
"Hspace =" 12 "src =" http://book.csdn.net/bookfiles/11/3/image011.gif "width =" 268 "align =" Left "> the dopost method of jsonexample servlet serves JSON requests. It first calls the readjsonstr-ingfromrequestbody method to obtain the JSON string from the request body, creates an instance of jsonobject, and provides the JSON string to the jsonobject constructor. Jsonobject automatically parses JSON strings when an object is created. Once a jsonobject is created, you can use each get method to obtain the object attributes you are interested in. The getstring and getint methods are used to obtain the year, make, model, and color attributes. These attributes are connected to form a string that is returned to the browser and displayed on the page. Figure 3-8 shows the server response after reading the JSON object. Jsonexample.html is displayed in code, and jsonexample. Java is displayed in code list 3-12. Code List 3-11  Jsonexample.html <! Doctype HTML public "-// W3C // dtd xhtml 1.0 strict // en" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <HTML xmlns = "http://www.w3.org/1999/xhtml">  Jsonexample. javapackage ajaxbook. chap3; import Java. io. *; import java.net. *; import Java. text. parseexception; import javax. servlet. *; import javax. servlet. HTTP. *; import Org. JSON. jsonobject; // import net. SF. JSON. *; public class jsonexample extends httpservlet {protected void dopost (httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {string JSON = readjsonstri Ngfromrequestbody (request); // use the JSON-Java binding library to create a JSON object in Java jsonobject = NULL; try {// If JSON-lib is used, the previously introduced package was changed to // import net. SF. JSON. *; // here, change to // jsonobject = jsonobject. fromobject (JSON); // fromobject (object) is static. Fromstring (string) can also be used, but fromstring is not recommended officially. Jsonobject = new jsonobject (JSON);} catch (parseexception PE) {system. out. println ("parseexception:" + PE. tostring ();} string responsetext = "you have a" + jsonobject. getint ("year") + "" + jsonobject. getstring ("make") + "" + jsonobject. getstring ("model") + "" + "that is" + jsonobject. getstring ("color") + "in color. "; response. setcontenttype ("text/XML"); response. getwriter (). print (respons Etext);} 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 ();}}

 

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.