JSON implementation code in jQuery

Source: Internet
Author: User
Tags tojson

The JSON format description can be seen here, which is very detailed and still Chinese.

JSON format description

Note that attribute names in JSON must be enclosed by quotation marks.

Use JSON in jQuery

JQuery is a widely used script library. How can I use JSON in jQuery?

Parse JSON

JQuery provides internal support for JSON parsing,

The jQuery. parseJSON function provides resolution support. For details, see here.
Copy codeThe Code is as follows:
Var obj = jQuery. parseJSON ('{"name": "John "}');
Alert (obj. name = "John ");

Use an object to generate a JSON string

JQuery does not provide a method to directly convert a common JavaScript Object To a json string. You can use the following extension library.

Jquery-json extension Library

This library is used to extend jQuery. For JSON usage, two methods are extended.

The toJSON method is used to serialize a common JavaScript Object into a JSON string.
Copy codeThe Code is as follows:
Var thing = {plugin: 'jquery-json', version: 2.3 };
Var encoded = $. toJSON (thing); // '{"plugin": "jquery-json", "version": 2.3 }'

The evalJSON method parses a JSON string into a common JavaScript Object.
Copy codeThe Code is as follows:
Var thing = {plugin: 'jquery-json', version: 2.3 };
Var encoded = $. toJSON (thing); // '{"plugin": "jquery-json", "version": 2.3 }'
Var name = $. evalJSON (encoded). plugin; // "jquery-json"
Var version = $. evalJSON (encoded). version; // 2.3

This extended: http://code.google.com/p/jquery-json/

Use jQuery with WCF
Client

$. Post in jQuery can directly send a request to the server to parse the data returned by the server in JSON format. However, pay attention to the following points:

The request content type must be in json format, which can be completed through the jQuery-json extension library above. Note that the requested contentType must also be described in text/json, the default post request uses normal name-value pairs. Therefore, the contentType is application/x-www-form-urlencoded. ajaxSetup:
Copy codeThe Code is as follows:
// Ajax settings
$. AjaxSetup ({contentType: 'text/json '});

In this way, the request content type is set to the required type.

Second, the actual request content must be in JSON format, which can be achieved through $. toJSON of the extension library, for example:

$. ToJSON ({x: 2, y: 3 })

In this way, if the server provides a service method Sum, the definition is as follows:
Copy codeThe Code is as follows:
Public int Sum (int x, int y)
{
Return x + y;
}

You can call it as follows. Note that the data returned by WCF is in attribute d.
Copy codeThe Code is as follows:
// Ajax settings
$. AjaxSetup ({contentType: 'text/json '});
$ ("# WcfBtn"). click (function (){
$. Post ("Service1.svc/Sum", $. toJSON ({x: 2, y: 3}), function (data ){
Alert (data. d );
});
});

Server Configuration
First, add the Label [System. ServiceModel. Activation. AspNetCompatibilityRequirements (
RequirementsMode = System. ServiceModel. Activation. AspNetCompatibilityRequirementsMode. Allowed)]Copy codeThe Code is as follows:
// #1
// Add this label to be used in the script
[System. ServiceModel. Activation. AspNetCompatibilityRequirements (
RequirementsMode = System. ServiceModel. Activation. AspNetCompatibilityRequirementsMode. Allowed)]
// #2
// You also need to set the website configuration file
Public class Service1: IService1
{
Public int Sum (int x, int y)
{
Return x + y;
}
}

Then, in the website configuration file, configure the following.
Copy codeThe Code is as follows:
<System. serviceModel>
<! -- To support calling specific configurations of the WCF Service on a browser -->
<ServiceHostingEnvironment aspNetCompatibilityEnabled = "true">
<ServiceActivations>
<! -- Address of the relativeAddress Service
Service implementation service type, full name, including namespace, and even assembly
Factory is provided by the WCF system and used directly
-->
<Add relativeAddress = "Service1.svc" service = "MServer. Service1" factory = "System. ServiceModel. Activation. WebScriptServiceHostFactory"
/>
</ServiceActivations>
</ServiceHostingEnvironment>
<Behaviors>
<ServiceBehaviors>
<Behavior name = "">
<ServiceMetadata httpGetEnabled = "true"/>
<ServiceDebug includeExceptionDetailInFaults = "false"/>
</Behavior>
</ServiceBehaviors>
</Behaviors>
</System. serviceModel>

Example of jQuery using JSON
Copy codeThe Code is as follows:
//// // 1. in HTML, There is a form like this:
<Form method = "post" name = "searchform" id = "searchform" method = "/sek. go">
<Input name = "query" value = "" type = "text" id = "query"/>
<Input type = "submit" value = "query"> </input>
</Form>
//// // Of course, to use the Js function in HTML, you must add
<Script type = "text/javascript" src = "/style/js/ajax. js"> </script>
///// // 2. Add the following code to the ajax. js file:
Function userSearch (){
Var query = $ ("# searchform input [@ name = 'query']"). val ();
$. Post ("/userSearch.htm", {query: query}, function callback (json ){
Var userlist = $. parseJSON (json );
UserList (userlist );
});
}
/*************************************** ****
Explanation:
1) "# searchform input [@ name = 'query']"; indicates that the input tag (whose name attribute value is 'query') with the id of searchform is selected.
2) $ (""). val () means to get the value of the selected Attribute;
3) In $. post (), the first parameter is to specify the target servlet, that is, the servlet to which the post request is sent.
The second item is the data carried by the post request. The key or name before ":" is followed by value;
The third item is the callback function. If the parameter exists, it indicates that the value returned from the servlet is processed. The callback function here is to convert the JSON object json into the JS object userlist, then pass the JS object to the userList function.
3. the post request carries a parameter named query to the backend for processing in the servlet:
// Retrieve post data from a parameter named "query"
String query = request. getParameter ("query ");
If (query! = Null &&! Query. isEmpty ()
&&! Query. trim (). inclusignorecase ("")){
// If the value of "query" is not empty, use 'query' to construct an HQL statement.
String hql = "from TUser as user where user. userName like '" + query + "% '";
// Query the database table TUser and obtain a table structure.
List list = weilav3TUserDAO. getListByHQL (hql );
If (list! = Null &&! List. isEmpty ()){
// If the list is not empty, convert it to a JSON object and store it in jsonArray.
JSONArray jsonArray = JSONArray. fromObject (list );
// Return the JSON object containing the query result to the page
Response. setContentType ("text/html; charset = UTF-8 ");
PrintWriter out = response. getWriter ();
Out. println (jsonArray );
......
} Else {......}
**************/

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.