The $. getjson method of jquery can be used to asynchronously obtain the JSON string returned by the server.
$. Getjson method syntax
$. Getjson (URL, parameters, callback) |
Parameters |
|
URL |
(String) the URL of the server resource to be interacted with through the get method. |
Parameters |
An object. Its attribute is used as a "key/value" to construct a query string and append it to a URL. It is also a pre-formatted and Uri-encoded query string. |
Callback |
(Function) callback function, called when the request is complete. Parse the response body as a JSON string. The value of this string is passed to this callback function as the first parameter, and the response status is passed to this function as the second parameter. |
Return Value |
Xhr instance |
The following is an example.
ClientCode:
<HTML xmlns = "http://www.w3.org/1999/xhtml">
Main server code:
Using system; using system. collections. generic; using system. web; using system. web. ui; using system. web. UI. webcontrols; using system. web. script. serialization; // applicable. netframework 3.5 Public partial class server: system. web. UI. page {protected void page_load (Object sender, eventargs e) {If (! Page. ispostback) {// list <person> Per = new list <person> (); // per. add (new person ("Zhang San", 18); // per. add (new person ("", 19); // javascriptserializer jsonhelper = new javascriptserializer (); // string JSON = jsonhelper. serialize (PER); // response. write (JSON); response. write (getjsondata () ;}} protected string getjsondata () {string STR = string. empty; // pay special attention to the JSON return format. If the format is incorrect, the client's callback function STR = "[{\" Name \ "cannot be called normally \": \ "Zhang San \", \ "Age \": \ "14 \"}, "+" {\ "Name \": \ "Li Si \", \ "Age \": \ "17 \"}, "+" {\ "Name \": \ "Wang Wu \", \ "Age \": \ "19 \"}] "; return STR;} public class person {private string name; private int age; Public string name {get {return name ;} set {name = value ;}} public int age {get {return age;} set {age = value ;}} public person (string name, int age) {This. name = Name; this. age = age ;}}}
RunProgram, Result
It doesn't matter if you are not familiar with the JSON format. You can use the help class formatted as json in the system. Web. Script. serialization (Framework 3.5) namespace. We can make the Code Annotated in the page_load event on the server available. Comment out the sentence response. Write (getjsondata. Run the program again and the result is correct, as shown in. It directly formats the class as a JSON string, saving a lot of time.
Download demo