ASP.net jQuery calls webservice to return json data, jqueryjson

Source: Internet
Author: User

ASP.net jQuery calls webservice to return json data, jqueryjson

During the winter vacation, I tried to use jQuery to write several asynchronous request demos,

However, this is a common webform page. Generally, most WebServices are used.

Recently, when I was writing back-end management, I wanted to Implement Asynchronous display and modification of some information,

This is the first time that ajax is actually used. It took an hour to display simple information.

There are two problems between them. Write it down and share it with you, so as to deepen your impression.

If there is any error, please point it out.

 

Front-end js Code:

 1     <script type="text/javascript"> 2         $(function () { 3             $("#details").hide(); 4             $(".details").click(function () { 5                 showdetails($(this).attr("id")); 6             }); 7         }) 8  9         function showdetails(id) {10             $.ajax({11                 url: "article.asmx/GetArticleByID",12                 type: "POST",13                 datatype: "json",14                 data:'{ id: ' + id + ' }',15                 contentType: "application/json; charset=utf-8",16                 success: function (data) {17                     var json = null;18                     try {19                         json = eval('(' + data.d + ')');20                     }21                     catch (e) {22                         alert(e.message);23                     }24                     $("#id").text(json.ID);25                     $("#title").text(json.Title);26                     $("#time").text(json.Time);27                     $("#text").text(json.Text);28                     $("#details").show();29                 }30             });31     </script>

Front-end html code

1 // click <td> <a class = "details" id = "<% = Convert. toInt32 (article. ID) %> "> details </a> </td> 3 4 // place where information is inserted 5 <div id =" details "> 6 <table> 7 <tr> 8 <td id = "id"> </td> 9 <td id = "title"> </td> 10 <td id = "time"> </td> 11 <td id = "text"> </td> 12 </tr> 13 </table> 14 </div>

 

Webservice code

1 [WebService (Namespace = "http://tempuri.org/")] 2 [WebServiceBinding (ConformsTo = WsiProfiles. basicProfile1_1)] 3 [System. componentModel. toolboxItem (false)] 4 // to allow ASP.. net ajax calls this Web service from a script. uncomment the following lines. 5 [System. web. script. services. scriptService] 6 public class article: System. web. services. webService 7 {8 9 [WebMethod] 10 public string GetArticleByID (int id) 11 {12 ArticleBLL article = new ArticleBLL (); 13 article = ArticleBLL. getArticleByID (id); 14 15 // string s = string. empty; 16 // s = "{\" id \ ": \" "+ article. ID + "\", \ "title \": \ "" + article. title + "\", \ "text \": \ "" + article. text + "\", \ "time \": \ "" + article. time + "\"} "; 17 // return s; 18 19 JavaScriptSerializer js = new JavaScriptSerializer (); 20 return js. serialize (article); 21 22 // Context. response. write (s); 23 // Context. response. end (); 24} 25}

 

The first problem encountered was that Error 500 was reported during information transmission, and the error was found to be in the data format,

Added contentType: "application/json; charset = UTF-8,

This statement tells the server that the previous json format information is passed, so an error message will be returned if the parsing fails.

Data to be written

Data: '{id:' + id + '}'

Data must be a "JSON object string" instead of a "JSON" object.

The reason is that jquery will serialize the JSON object to the standard POST form. Your {id: id} here will become the form of id = 3, while ASP. NET WebService requires JSON data, so you must convert your data into a JSON string.

 

The second problem is that the returned data format is correct when the request is successful but cannot be displayed.

The data returned by default is in xml format. Here I use JavaScriptSerializer js = new JavaScriptSerializer (); return js. Serialize (article); to return json format information.

The final commented-out code is displayed on the Internet. It outputs plain text and can be recognized by the browser. However, I did not test it and it should be OK.

 

It turns out to be resolved. This process is called deserialization.

In the success callback function, jquery obtains the actual json object by obtaining the d attribute of the returned string obtained by webservice under eval.

If the returned information is {"d": "{\" Title \ ": \" article Title, how can we get the value of the msg attribute?

First of all, it must be clear that the string in json format actually obtained after webservice is called is {"d": "{\" Title \": \ "article title \"}"},

Jquery uses this string to generate only one json object, that is, d. d stores the json Format String information returned by the webservice method, instead of the json object,

Therefore, the ID information cannot be obtained through data. d. ID. Instead, var json = eval ('+ data. d +') is required to generate the actual json object, and josn. ID is the required information.

 

In fact, xml data can be directly parsed, but it is a little more troublesome than json.

Http://www.cnblogs.com/qiantuwuliang/archive/2009/11/23/1609117.html

This article describes how to parse xml data.

 

Reference http://www.cnblogs.com/tianguook/archive/2010/12/04/1896485.html

Reprinted, Please retain the source.

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.