Explore the message transmission mode in AJAX (II)

Source: Internet
Author: User

In the previous article "exploring the message transmission mode in AJAX (I)", I mainly introduced the transmission modes in the common string Plain-text string and XML format, however, in actual development and application, these two methods can basically meet our needs, but in the case of complex object transmission, it is not ideal to use the two transmission modes described above. This article introduces a lightweight data exchange format JSON (JavaScript Object Notation) in combination with "exploring the message transmission mode in AJAX (I ), this is a crpt method used to describe objects. JSON is a substitute for XML.

Before using JSON for data transmission, let's take a look at several simple JSON syntaxes to lay the foundation for those who are not familiar with JSON and want to read this article. JSON and XML are also simple text formats. Compared with XML, it is easier to read and check with the naked eye. At the syntax level, the difference between JSON and other formats is that it separates data characters. The separators in JSON are limited to single quotes, Parentheses, braces, braces, colons, and commas. The following is a JSON payload:

{"UserID":"0001","UserName":"ZhangSan","UserAge":"22"}

It looks simple. The keys and values correspond one to one (Key ---- Value). Let's look at a complicated JSON payload:

{Employees:[       {"EmployeeID":"1","LastName":"Davolio","City":"Seattle","Country":"USA"},       {"EmployeeID":"2","LastName":"Fuller","City":"Tacoma","Country":"USA"}           ]}

From the JSON above, we can clearly see that the Employees object contains two pieces of data, and we rewrite it with XML, as shown below:

<?xml version='1.0' ?><Employees><Employee><EmployeeID>1</EmployeeID><LastName>Davolio</LastName><City>Seattle</City><Country>USA</Country></Employee><Employee><EmployeeID>2</EmployeeID><LastName>Fuller</LastName><City>Tacoma</City><Country>USA</Country></Employee><Employees>

For more detailed use of JSON and syntax format, please refer to relevant information, here I recommend a website http://www.json.org /). You can also search for articles from the predecessors in the garden. Truly's article "in-depth introduction to JSON" introduces JSON, which is very detailed in my personal experience.

As mentioned above, we still use an example to demonstrate the use of JSON, or it will become an example. This article is the continuation of "exploring the message transmission mode (I) in AJAX". The sample code is based on this article. Add a new method in WebService to provide the employee ID) query the information of the employees whose number is less than or equal to (<=:

[WebMethod] public string GetEmployeeWithJson (int id) {// query the EmployeeID, LastName, City, Country fields; dt = DataAccess. getEmployees (id); StringBuilder json = new StringBuilder (); json. append ("{Employees: ["); int I = 0; string result = string. empty; foreach (DataRow row in dt. rows) {json. append ("{"); json. append (@ "EmployeeID" ":" + row ["EmployeeID"] + @ ","); json. append (@ "" LastName ":" + row ["LastName"] + @ ","); json. append (@ "City" ":" + row ["City"] + @ ","); json. append (@ "Country" ":" + row ["Country"] + @ "}"); if (++ I = dt. rows. count) {json. append ("}]");} json. append (",");} json. append ("}"); result = json. toString (). remove (json. length-2, 1); // remove "," result = result. remove (result. length-3, 1); // remove "}" return result ;}

DataAccess. GetEmpoyees (int id) method definition:

Public static DataTable GetEmployees (int id) {string comment text = "select EmployeeID, LastName, City, Country from Employees"; Comment text + = "where EmployeeID <=" + id; return Exce (plain text); // Execute SQL to return DataTable}

Here, you may have some questions about why a "," and "}" will be removed after this method, which is added when the JSON string is dynamically constructed above, if the return value of the method is not removed, it is as follows:

In order to allow the client to correctly deploy this JSON through JavaScript, an extra "," and "}" after the returned value must be removed, as shown below:

At this point, the server is ready for work. Let's take a look at how the client is implemented. First, we provide the ScriptManager control for the aspx page, and then introduce WebService to call WebService methods on the client:

<asp:ScriptManager ID="ScriptManager1" runat="server"><Services><asp:ServiceReference Path="MessageWebService.asmx" /></Services></asp:ScriptManager>

Provide a down-list control to allow the user to select employee numbers. Here, by setting the default value, data may be read from the database in the actual development application, which is only used for program demonstration ), send the request with a twist and display the result in divresultEmployee:

Select the employee ID range less than (<) <asp: DropDownList ID = "ddlEmployeeID" runat = "server"> <asp: ListItem> 1 </asp: ListItem> <asp: listItem> 2 </asp: ListItem> <asp: ListItem> 3 </asp: ListItem> <asp: ListItem> 4 </asp: ListItem> <asp: listItem> 5 </asp: ListItem> <asp: ListItem> 6 </asp: ListItem> <asp: ListItem> 7 </asp: ListItem> <asp: listItem> 8 </asp: ListItem> </asp: dropDownList> <input id = "Query" type = "button" value = ""/> <br/> 

Similarly, we need to initialize the client's reference to the control and add execution events to the button:

var ddlEmployeeID;var divResult;var buttonQuery;    function pageLoad(){   ddlEmployeeID = $get("<% = ddlEmployeeID.ClientID %>");   divResult = $get("resultEmployee");   buttonQuery = $get("Query");   $addHandler(buttonQuery,"click",onButtonClicked);   onButtonClicked(null);}

When you click the button, the click event is triggered, the onButtonClicked method is called, and the WebService method is called:

Function onButtonClicked (eventElement) {// obtain the selected employee ID var employeeID = ddlEmployeeID. options [ddlEmployeeID. selectedIndex]. value; // call WebService to obtain MessageWebService. getEmployeeWithJson (employeeID, onJsonCallBack );}

Initiate a request to the server in asynchronous mode, pass the employee ID as a parameter to the server, and process the returned data through the onJsonCallBack callback method, as shown below:

// Dynamically construct the html table var html = new Sys Based on the returned data. stringBuilder (); html. append ("<table width = '460px 'cellspacing = '1' cellpadding = '2' border = '0' bgcolor =' #999999 '>"); html. append ("<tr>"); html. append ("<td bgcolor = 'gold' align = 'center'> <B> EmployeeID </B> </td>"); html. append ("<td bgcolor = 'gold' align = 'center'> <B> LastName </B> </td>"); html. append ("<td bgcolor = 'gold' align = 'center'> <B> City </B> </td>"); html. append ("<td bgcolor = 'gold' align = 'center'> <B> Country </B> </td>"); html. append ("</tr>"); for (var I = 0; I <data. employees. length; I ++) {html. append ("<tr>"); html. append ("<td bgcolor = 'white'>" + data. employees [I] ["EmployeeID"] + "</td>"); html. append ("<td bgcolor = 'white'>" + data. employees [I]. lastName + "</td>"); html. append ("<td bgcolor = 'white'>" + data. employees [I]. city + "</td>"); html. append ("<td bgcolor = 'white'>" + data. employees [I]. country + "</td>"); html. append ("</tr>");} html. append ("</table>"); resultEmployee. innerHTML = html. toString ();

Complete client code:

<% @ Page Language = "C #" AutoEventWireup = "true" CodeFile = "AjaxMessageJson. aspx. cs" Inherits = "AjaxMessageJson" %> <! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 

If no data is returned from the server, only the header information is output on the client page.

If any data is returned, the table is dynamically constructed and displayed on the page, as shown below:

  1. Explore the message transmission mode in AJAX (I)
  2. Analysis on the ten reasons for using AJAX
  3. A simple method to use AJAX in ASP. NET
  4. Use AJAX to build better Web Applications

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.