Implementation code for using JSON in JQuery _jquery

Source: Internet
Author: User
Tags tojson

The format description of JSON can be seen here, in very detail, or in Chinese.

JSON Format Description

It is particularly noteworthy that property names in JSON are enclosed in quotes.

Using JSON in JQuery

jquery is a widely used script library now, so how do you use JSON in jquery?

Parsing JSON

The inherent support for parsing JSON has been provided in JQuery,

The Jquery.parsejson function provides parsing support, as detailed in the instructions here.

Copy Code code as follows:

var obj = Jquery.parsejson (' {' name ': ' John '} ');
Alert (Obj.name = = "John");

Using objects to generate JSON format strings

In JQuery, there is no way to directly convert a normal JavaScript object into a JSON string, which can be done using the following extension library.

Jquery-json Extension Library

This library is used to extend JQuery, with two methods extended for use with JSON.

The Tojson method is used to serialize an ordinary JavaScript object into a JSON string.
Copy Code code as follows:

var thing = {plugin: ' Jquery-json ', version:2.3};
var encoded = $.tojson (thing); ' {' plugin ': ' Jquery-json ', ' Version ': 2.3} '

The Evaljson method resolves a JSON string into a normal JavaScript object.
Copy Code code 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

Download address for this extension: http://code.google.com/p/jquery-json/

use JQuery to work with WCF
Client

The $.post in JQuery can send a request directly to the server to parse the data returned by the server in JSON, but you need to be aware of the following points:

The requested content type must be in JSON format, which can be done through the Jquery-json extension library above, requiring special attention in the requested ContentType must also use Text/json to explain that the default post uses normal name-value pairs, so cont Enttype is: application/x-www-form-urlencoded, which can be set by $.ajaxsetup:
Copy Code code as follows:

Ajax settings
$.ajaxsetup ({contentType: ' Text/json '});

In this way, the requested content type is set to the desired type.

Second, the actual request content must be in JSON mode, which can be implemented through the $.tojson of the extension library, for example:

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

This way, if the server side provides a service method Sum, it is defined as follows:
Copy Code code as follows:

public int Sum (int x, int y)
{
return x + y;
}

You can call it as follows. Note that the data that WCF returns is in attribute D.
Copy Code code 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-side configuration
First, add a label to the service: [System.ServiceModel.Activation.AspNetCompatibilityRequirements (
Requirementsmode = System.ServiceModel.Activation.AspNetCompatibilityRequirementsMode.Allowed)]
Copy Code code as follows:

#1
In order to be used in the script, this tag must be added
[System.ServiceModel.Activation.AspNetCompatibilityRequirements (
Requirementsmode = System.ServiceModel.Activation.AspNetCompatibilityRequirementsMode.Allowed)]
#2
The configuration file in the Web site also needs to be set
public class Service1:iservice1
{
public int Sum (int x, int y)
{
return x + y;
}
}

Then, in the configuration file for the Web site, configure the following.
Copy Code code as follows:

<system.serviceModel>
<!--to support specific configurations that invoke WCF services on the browser side-->
<servicehostingenvironment aspnetcompatibilityenabled= "true" >
<serviceActivations>
Address of the <!--relativeaddress Service
Service implementation type, full name, inclusive namespace, even assembly
Factory is provided by WCF system, directly used
-->
<add relativeaddress= "Service1.svc" service= "Mserver.service1" System.ServiceModel.Activation.WebScriptServiceHostFactory "
/>
</serviceActivations>
</serviceHostingEnvironment>
<behaviors>
<serviceBehaviors>
<behavior name= "" >
<servicemetadata httpgetenabled= "true"/>
<servicedebug includeexceptiondetailinfaults= "false"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>

examples of jquery using JSON
Copy Code code as follows:

1, in the HTML, there is such a form:
<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 in <script type= "Text/javascript" src= "/style/js/ajax.js" ></script>
2, then add the following code in 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);
});
}
/*******************************************
Explained as follows:
1), "#searchform input[@name = ' query ']" means: Select input label with ID searchform (Name property value ' query ')
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 this post request is sent.
The second item is the data carried by this post request, ":" Before the key or name, after the value;
The third item is the callback function, which, if the physical parameter, means to handle the value returned from the servlet, where the callback function is to convert JSON object JSON to a JS object userlist, and then pass the JS object into the function userlist
3. Post request carries the parameter named query to the background, processing in the servlet:
Remove the data from the post brought from the argument named "Query"
String query = request.getparameter ("query");
If query!= null &&!query.isempty ()
&&!query.trim (). Equalsignorecase ("")) {
If the value of "query" is not empty, use ' query ' to construct the HQL statement for the parameter
String hql = "from TUser as user where user.username like" + query + "%";
Query in the Tuser of the library table and get a table structure
List List = WEILAV3TUSERDAO.GETLISTBYHQL (HQL);
if (list!= null &&!list.isempty ()) {
If the list is not empty, it is converted to a JSON object and stored in Jsonarray
Jsonarray Jsonarray = jsonarray.fromobject (list);
The following is the return of the JSON object that contains the query results to the page
Response.setcontenttype ("Text/html;charset=utf-8");
PrintWriter out = Response.getwriter ();
Out.println (Jsonarray);
......
}else {...}
**************/

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.