Detailed description of JQuery Ajax in asp.net, jqueryajax

Source: Internet
Author: User

Detailed description of JQuery Ajax in asp.net, jqueryajax

With JQuery, the use of Ajax has become more and more convenient, but there will still be more or less pain problems in a short period of time. This article summarizes some issues that should be paid attention to when using JQuery Ajax. If there are any inappropriate or imperfect issues, you are welcome to correct and supplement them.

This article will discuss the three methods of Ajax request aspx, ashx, and asmx.

First, let's look at the request aspx.

There are two methods for Ajax requests on the Aspx page:

1. By using the get or post method, pass the page address as the url parameter value, and attach some markup parameters to directly request. In this way, Ajax is hailed as "fake Ajax" by some people. On the surface, the page is not refreshed. In fact, the background execution is the same as refreshing the page.

In fact, in this case, you can also request specific methods on the page. As long as you use the included parameters to determine, you can "request" specific methods.

The following shows how to request two different pages using two different methods. The code is extracted, and the detailed code can be downloaded at the end of the article.

Front-end:

// Method of directly requesting the page $ (function () {/* $. get ("RequestPage. aspx ", {" token ":" ajax "}, function (data) {$ (" # dataShow "). text (data) ;}); */$. ajax ({type: "Post", url: "ResponsePage. aspx ", // data:" {'Token': 'ajax '} ", // parameters cannot be passed in this way. Please tell us the reason. Data: "token = ajax", success: function (data) {$ ("# dataShow"). text (data );}});})

Background:

Protected void Page_Load (object sender, EventArgs e) {if (! This. IsPostBack) {if (Request ["token"]? "") = "Ajax") {// The following content can be placed in a method, and then the "token" mark is used to determine which method to execute. Response. Write ("I directly requested the text returned from the aspx page! "); Response. End ();}}}

The returned values of the preceding request are strings, that is, the text ype is of the text or html type.

What if I want the data returned by the request to be in xml or json format?

If it is in xml format, you need to add a Response. contentType = "application/xml"; note that the content in Write must be a string that can be parsed as xml, for example, "<my> 123 </my>" is acceptable, and "123" is not acceptable, because responseXml in the returned information is equal to null. For example:

Front-end:

$. Ajax ({type: "Post", url: "ResponsePage. aspx ", // data:" {'Token': 'ajax '} ", // parameters cannot be passed in this way. Please tell us the reason. Data: "token = ajax", // you do not need to specify the contentType, because the html of the entire page is returned after the specified value. If you do not know why, please answer the request. DataType: "xml", success: function (data) {alert (data) ;}, error: function (d, c, e) {alert (e );}});

Background:

// If the returned Response is xml, you must set Response as follows. contentType = "application/xml"; // If the returned response is xml, the returned string must be an xml document that can be parsed. Response. Write ("<my> 123 </my>"); Response. End ();

If it is in json format, Response. ContentType = "application/json" in the background code can be left blank without affecting the returned value. However, the value in Response. Write must be in json format, otherwise there will be an Invalid Json format error.

Front-end:

$. Ajax ({type: "Post", url: "ResponsePage. aspx ", // data:" {'Token': 'ajax '} ", // data must be in the form of {key: value}, which is a string, no. // Data: {token: "ajax"}, // This method is also feasible. Data: "token = ajax", // you do not need to specify the contentType, because jquery automatically adds contentType = "application/x-www-form-urlencode ". DataType: "json", success: function (data) {alert (data) ;}, error: function (d, c, e) {alert (e );}});

Record: If you directly request a page, if data uses the string format "{'Token': 'ajax '}", jquery cannot be converted to the form of token = ajax.

In the jquery document, you can use the data request page in the form of {key: value}. In this case, jquery automatically adds contentType = "application/x-www-form-urlencode ", the input data is automatically converted to key = value.

Background:

// If the returned Response is xml, you must set Response as follows. contentType = "application/json"; // If the returned response is xml, the returned string must be in the xml document format that can be parsed. Response. Write ("[123]"); Response. End ();

2. Request methods in the background of the aspx page.

In fact, the above direct request PAGE method also introduced a solution for the method in the request page, that is, to pass a parameter in the front-end ajax as a tag, for example, the "token" above is used to judge the token value in the page_load in the background. Different methods are executed based on different values. The following describes how to directly execute the method in the background of the page.

(1) When the get or post method is simple, the contentType and dataType cannot be set, so even if the request is a method in the page, the last request is the current page, the returned value is still the html content of the current page. Therefore, the simple method is not suitable for the request method.

(2) When using a non-simple method, whether post or get, if dataType is xml, text, or htm, the returned value is still the content of the entire html page. So if you want to think of the value, set dataType to "json". Do not forget to set contentType to "application/json; charset = UTF-8". Do not set this, json cannot be returned. In addition, you must ensure that the requested method in the background is static and the [webmethod] mark must be added, and the requested method must be public.

Front-end:

$. Ajax ({type: "post", url: "RequestPage. aspx/RequestedMethod ", contentType:" application/json; charset = UTF-8 ", dataType:" json ", success: function (res) {alert (" success: "+ res. d); // note that d must be added after this point to obtain the string information. As to why d should be added, you can see the returned response through chrome) o}, error: function (xmlReq, err, c) {alert ("error:" + err );}});

Background:

// The background method [WebMethod] [ScriptMethod (UseHttpGet = true)] // if you want to use the POST request, remove the public static string RequestedMethod () {return "[123]";}

Direct use of post is no problem:

If the type is changed to "get", "500 internal error" will occur ". Error Message: {"Message": "try to use the GET request to call the method" RequestedMethod ", but this is not allowed.

The solution is to add a label [ScriptMethod (UseHttpGet = true)] To the POST method, and the ScriptMethod is in the System. web. script. services. in this way, the request can be sent in the frontend through the Get method. However, if this flag is added, the frontend cannot use POST for the request.

3. Request the method in the background of the aspx page with Parameters

Front-end:

$. Ajax ({type: "Post", url: "ResponsePage. aspx/RequestMethod1 ", data:" {'msg ': 'hello'} ", contentType:" application/json; charset = UTF-8 ", // do not forget this sentence. DataType: "json", success: function (res) {$ ("# dataShow "). text ("success:" + res. d); // note that there is a d. As for why do you use chrome to view the response, O (∩) O. }, Error: function (xmlReq, err, c) {$ ("# dataShow"). text ("error:" + err );}});

Background:

[WebMethod]public static string RequestMethod1(string msg){  return msg; }

In general, parameters are similar to those without parameters. The difference is that a data parameter must be passed during ajax requests. Note that the data must be a json string, otherwise, a json error is reported. Why? The contentType you passed is application/json.

Request for asmx (webservice)

When requesting webservice, it is mainly a method in webservice request. Do not forget the prompt "// to allow the use of ASP. net ajax calls this Web service from the script. Please cancel the comments to the downstream.

// [System. Web. Script. Services. ScriptService]"

The Processing Method of the Request webservice is similar to that of the background method of the request aspx page, but there are also some differences.

Features of the method in the requested webservice:

(1) The request method must be public.

(2) The method must have the [WebMethod] Mark.

(3) If you want to use the Get Method for a request, you must also have the [ScriptMethod (UseHttpGet = true)] Mark. When using the Get request Webservice method, it is not enough to add only this tag, but also modify the Web. the Config file allows WebService to support Get requests. Otherwise, "the URL ends unexpectedly with"/GetXmlByGet ", and the request format cannot be identified. "Error. To modify it, add the following red content in the System. web configuration section:

<System.web>……………<webServices>  <protocols>  <add name="HttpGet"/>  <add name="HttpPost"/>  </protocols> </webServices></System.web> 

(4) When requesting the xml data type, note that if the method returns the string type, the returned xml format is as follows:

If the method returns a string, the returned string is packaged in the <string> label and returned.

For example, the return value after the request is as follows:

[WebMethod] public string GetXmlByPost () {return "I requested the returned xml in Post mode ";}

Return Value:

<? Xml version = "1.0" encoding = "UTF-8"?> <String xmlns = "http://tempuri.org/"> I'm the xml returned by a Post request </string>

The red part is the string returned by the request method, and the others are automatically added. Therefore, when getting data through jquery in the previous console, You Should $ (res ). find ("string "). text (); if the method returns an xmlDocument object, it is the xml object constructed in the method.

For example, the return value after the request is as follows:

// Use the Get method to request xml. Note that the returned string must be in an xml format that can be parsed. [WebMethod] [ScriptMethod (UseHttpGet = true)] public System. Xml. XmlDocument GetXmlByGet () {string xml = "<? Xml version = \ "1.0 \" encoding = \ "UTF-8 \"?> <My> xml returned by a Get request </my> "; System. xml. xmlDocument doc = new System. xml. xmlDocument (); doc. loadXml (xml); return doc ;}

The returned response is:

<? Xml version = \ "1.0 \" encoding = \ "UTF-8 \"?> <My> I requested the returned xml through Get </my>

In this case, you can use $ (res). find ("my"). text () to retrieve data. At this time, the operation is completely the xml you have constructed.

(5) When a request returns JSON, it must be noted that the returned data is in the format of [d :{}]. When obtaining the data from the front-end, you must add one ". d ", the rest is similar to xml.

(6) There is not much to say about the Text type.

Request for ashx

The request for ashx is similar to the request for an apsx page. After all, data is returned through response. Write (string.

Note that the value of context. Response. ContentType is distinguished according to the value of dataType:

Text: "text/plain";

XML: "application/xml";

JSON: "application/json".

When dataType is xml, response. the string in Write (string) must conform to the xml format. When it is json, response. the string in Write (string) must conform to the json format. Otherwise, a parsing error will occur, which is the same as that on the aspx page.

If you want to use the session, add the reference System. Web. SessionState to the handler code, and let the handler inherit the IRequiresSessionState interface. Otherwise, errors may occur.

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

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.