Master Ajax, Part 1: server-side JSON

Source: Internet
Author: User
Tags object serialization php server php template

Use JSON for response and response in server scripts and programs


Document options

Print this page

Print this page

Level: Advanced

Brett D. McLaughlin, Sr.(Brett@newInstance.com), Writer and editor, o'reilly media, Inc.

August 28, 2007

InIn a recent article in this seriesYou have learned how to convert JavaScript objects into JSON format. This format is easy to send (and receive) data that corresponds to an object or even an object array. InThis seriesIn the last article, you will learn how to process data sent to the server in JSON format and how to reply to the script in the same format.

Real Value of JSON

As inPrevious articles in this seriesAs described in, JSON is a valid format for Ajax applications because it enables fast conversion between JavaScript objects and string values. Because Ajax applications are suitable for Sending plain text to server programs and receiving plain text, it is more desirable to generate text APIs than to generate text, JSON allows you to process local JavaScript objects without worrying about how to express them.

Developerworks Ajax Resource Center
Please visitAjax Resource CenterThis is an all-in-one center for Ajax programming model information, including many documents, tutorials, forums, blogs, wikis, and news. Any new information about AJAX can be found here.

XML can also provide similar text benefits, but several existing APIs used to convert JavaScript objects into XML are not as mature as json apis; sometimes, you must exercise caution when creating and processing Javascript objects to ensure that the processing can work with the selected XML session API. But for JSON, the situation is very different: it can process almost all possible object types, and will return you a very good JSON data representation.

Therefore, the biggest value of JSON is that javascript can beAs JavascriptInstead of the data format language. All the techniques you have learned about using JavaScript objects can be applied to your code without worrying about how to convert these objects into text. After that, you can call the following simple JSON method:

String myObjectInJSON = myObject.toJSONString();


Now you can send the result text to the server.




Back to Top

Send JSON to server

It is not difficult to send JSON to the server, but it is crucial and there are some important options to do. However, once you decide to use JSON, these options will be very simple and limited, so there are not many things to consider and focus on. It is important to be able to send the JSON string to the server, and it is best to do it as soon as possible and as simple as possible.

Use get to send JSON data with name/value pairs

The simplest way to send JSON data to the server is to convert it into text and then send it as the value of the name/value pair. It is important to note that the data in JSON format is a fairly long object and may appear as shown in Listing 1:

Listing 1. Simple JavaScript objects in JSON format

var people =  { "programmers": [    { "firstName": "Brett", "lastName":"McLaughlin",
"email": "brett@newInstance.com" },    { "firstName": "Jason", "lastName":"Hunter",
"email": "jason@servlets.com" },    { "firstName": "Elliotte", "lastName":"Harold",
"email": "elharo@macfaq.com" }   ],  "authors": [    { "firstName": "Isaac", 
"lastName": "Asimov", "genre": "science fiction" },    { "firstName": "Tad", 
"lastName": "Williams", "genre": "fantasy" },    { "firstName": "Frank", 
"lastName": "Peretti", "genre": "christian fiction" }   ],  "musicians": [    
{ "firstName": "Eric", "lastName": "Clapton", "instrument": "guitar" },   
{ "firstName": "Sergei", "lastName": "Rachmaninoff", "instrument": "piano" }   ]  }


If you want to send a name/value pair to the server, it should be as follows:

var url = "organizePeople.php?people=" + people.toJSONString();
xmlHttp.open("GET", url, true);
xmlHttp.onreadystatechange = updatePage;
xmlHttp.send(null);


This looks good, but there is a problem: there are spaces and various characters in JSON data, and Web browsers often have to try to compile it. To ensure that these characters do not cause confusion on the server (or when sending data to the server ),escape()Add the following in the function:

var url = "organizePeople.php?people=" + escape(people.toJSONString());
request.open("GET", url, true);
request.onreadystatechange = updatePage;
request.send(null);


This function can process spaces, diagonal lines, and any other content that may affect the browser, and convert them into available web characters (for example, spaces are converted%20The browser does not treat it as a space, but does not change it and directly transmits it to the server ). Then, the server will (usually automatically) convert them back to their original "face" after transmission ".

There are two disadvantages of this practice:

  • The URL string length is limited when a GET request is used to send large data blocks. Although this restriction is broad, the length of the object's JSON string representation may exceed your imagination, especially when using extremely complex objects.
  • When sending all data in plain text across networks, the security of data transmission exceeds your processing capability.

In short, the above are two restrictions on GET requests, not two simple things related to JSON data. When you want to send more content beyond the user name and surname, such as the selection in the form, you may need to pay more attention to the two. To process any confidential or extremely long content, you can use post requests.

Send JSON data using post requests

When you decide to use the POST request to send JSON data to the server, you do not need to make a lot of changes to the Code, as shown below:

var url = "organizePeople.php?timeStamp=" + new Date().getTime();
request.open("POST", url, true);
request.onreadystatechange = updatePage;
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
request.send(people.toJSONString());


Most of the Code, Understanding Ajax, part 1: Advanced requests and responses in Ajax"Has been seen, should be familiar with, Part 1 focuses on how to send post requests. The request is opened using post instead of get, and the Content-Type header is set to let the server know what data it can get. In this caseapplication/x-www-form-urlencodedIt allows the server to know that the text is sent, just as it gets from the regular HTML form.

Another simple prompt is the append time at the end of the URL. This ensures that the request will not be cached after it is sent for the first time, but will be re-created and re-issued after each call of this method; the URL varies slightly depending on the timestamp. This technique is often used to ensure that a new request is generated every time a script post is sent, and the Web server does not try to cache responses from the server.

JSON is just text

Whether get or post is used, the key is that JSON is only text. Because no special encoding is required and each server-side script can process text data, JSON can be easily used and applied to the server. If JSON is in binary format or some weird text encoding, the situation is not that simple. Fortunately, JSON is only the regular text data (just as the data that the script can receive from form submission, as can be seen in the post segment and Content-Type headers), you do not have to worry too much when sending data to the server.




Back to Top

Explain JSON on the server

Once you have compiled the client JavaScript code, allowed users to interact with web forms and web pages, and collected the information required for processing sent to the server program, the server becomes the main character of an application (if an Asynchronous Server program is called, it may be a so-called "Ajax application. At this time, your selection on the client (for example, using a JavaScript Object and then converting it into a JSON string) must match the selection on the server side, for example, which API is used to decode JSON data.

Two steps for processing JSON

Regardless of the language used on the server, two steps are required to process JSON on the server.

  1. Find the corresponding JSON parser/toolbox/helper API for the language used to write the server-side program.
  2. Use the JSON parser/toolbox/helper API to retrieve request data from the client and convert the data into something that the script can understand.

The above is about what we should know. Next, we will introduce each step in detail.

Search for the JSON parser

The best resource for finding a JSON parser or toolbox is the JSON site (for links, seeReferences). In addition to understanding all aspects of the format itself, you can also find various JSON tools and Resolvers through various links, from ASP to Erlang, to Pike, and then to Ruby, everything. You only need to download the toolbox for the language used to write your own scripts. To enable server scripts and programs to use this toolkit, you can select, expand, or install it as needed (if C #, PHP, or lisp is used on the server, is more variable ).

For example, if you are using PHP, you can simply upgrade it to PhP 5.2 and use it to complete the operation. The latest version of PHP contains the JSON extension by default. In fact, it is also the best way to process JSON when using PHP. If Java Servlet is usedorg.jsonPackage is obviously a good choice. In this case, you can download json.zip from the JSON web site and add the included source files to the Project Build directory. After these files are compiled, everything is ready. The same procedure can also be used for other Supported languages. The language you use depends on your proficiency in the language, and it is best to use the language you are familiar.

Use the JSON parser

Once the available resources of the program are obtained, the only thing left is to find the appropriate method for calling. For example, suppose PHP uses a JSON-PHP template:

// This is just a code fragment from a larger PHP server-side script
require_once('JSON.php');

$json = new Services_JSON();

// accept POST data and decode it
$value = $json->decode($GLOBALS['HTTP_RAW_POST_DATA']);

// Now work with value as raw PHP


This template can be used to convert all the obtained data (array format, multiline, single-value, or any content in the JSON Data Structure) to the native PHP format and place it in$valueVariable.

If you useorg.jsonThe following code is used:

public void doPost(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {

  StringBuffer jb = new StringBuffer();
  String line = null;
  try {
    BufferedReader reader = request.getReader();
    while ((line = reader.readLine()) != null)
      jb.append(line);
  } catch (Exception e) { //report an error }

  try {
    JSONObject jsonObject = new JSONObject(jb.toString());
  } catch (ParseException e) {
    // crash and burn
    throw new IOException("Error parsing JSON request string");
  }

  // Work with the data using methods like...
  // int someInt = jsonObject.getInt("intParamName");
  // String someString = jsonObject.getString("stringParamName");
  // JSONObject nestedObj = jsonObject.getJSONObject("nestedObjName");
  // JSONArray arr = jsonObject.getJSONArray("arrayParamName");
  // etc...
}


Referorg.jsonPackage documentation (for more information, seeReferencesFor more information.(Note: If you want to obtain details about the org. JSON or other JSON toolkit, you can send me an email. Your letter will help me decide what to write in the future !)




Back to Top

Conclusion

At this point, you should have a basic understanding of how to process JSON on the server. This article and the seriesPart 1It not only provides technical help, but also shows you how flexible and powerful the JSON format is. Even if you don't use JSON in every application, the toolbox of excellent Ajax and JavaScript programmers always has no need for JSON.

Of course, I would like to share your JSON usage experience and the language in which you are more adept at processing JSON data on the server. You can access Java and XML newsgroups (for links, seeReferencesContact me. Enjoy JSON and text data formats.

References

Learning

  • You can refer toOriginal ENGLISH.


  • Understanding AjaxSeries: Read previous articles in this series.Part 1This section focuses on how to send and receive advanced Ajax requests and responses.
  • JSON site: For collection sites of all JSON content, find the best resource site for the JSON parser and toolbox.
  • ReadOrg. JSON package.
  • Xml.com: One of the easiest-to-understand online resources. If you are not an experienced XML programmer, learn about XML from here!
  • "Ajax for Java developers: Build Dynamic Java applications"(Philip McCarthy, developerworks, September 2005): a Java perspective on server-side Ajax.
  • "Ajax for Java developers: Java object serialization of AJAX"(Philip McCarthy, developerworks, October 2005): explains how to send objects over the network and interact with Ajax from a Java perspective.
  • "Use ajax to call the soap web service. Part 1: Construct a web service client"(James Snell, developerworks, October 2005): this is a fairly advanced article about integrating Ajax with existing soap-based Web Services.
  • TheDom Homepage: Get started with all Dom-related technologies.
  • Dom Level 3 Core Specification: Understand the definition of the Core Document Object Model, from available types and attributes to using DOM in various languages.
  • The ecmascript language Bindings for Dom: Any JavaScript programmer who wants to use DOM in code should read this specification.
  • "Ajax: A New Approach to Web Applications": Read this first Ajax term. This is a must-read article by all Ajax developers.
  • Head rush Ajax (Brett McLaughlin, O 'Reilly media, Inc.): Learn the ideas in this article and stick them to your mind: head first style.
  • Java and XML, Second Edition (Brett McLaughlin, O 'Reilly media, Inc.): see the author's discussion of XHTML and XML Conversion.
  • Javascript: the definitive guide (DAVID Flanagan, O 'Reilly media, Inc.): explores a large number of guiding principles for processing Javascript and dynamic web pages. The upcoming version adds two chapters on Ajax.
  • Head first HTML with CSS & XHTML (Elizabeth and Eric Freeman, O 'Reilly media, Inc): learn more about standardizing HTML and XHTML and how to apply CSS to HTML.
  • "Getting started with XML"Page: If you want to learn XML, but do not know where to start, you can access the XML-centered update resource in the XML area.
  • On developerworksAjax Resource Center: This is an all-in-one center for Ajax. Visit the resources here and use Ajax for Development immediately.
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.