Using jquery AJAX-related usage summary in ASP.

Source: Internet
Author: User
Tags parse error string back urlencode
This article mainly introduces the details of jquery Ajax in the use of the summary of ASP, small series feel very good, and now share to everyone, but also to make a reference. Let's take a look at it with a little knitting.

Since the use of Jquery,ajax has become more and more convenient, but the use of more or less will appear in some short-term pain in the problem. This article briefly summarizes some of the issues that should be noted in the use of jquery Ajax, such as inappropriate or imperfect places, you are welcome to correct and Add.

This article will be discussed from Ajax request aspx, ASHX, and asmx three ways.

First look at the case of requesting ASPX

An AJAX request for an ASPX page can be in two ways:

1, by using the Get or POST method, the page address is passed the value of the URL parameter, and with some tag parameters, direct request. This way of Ajax by some people as "fake Ajax", the surface does not refresh the page, in fact, the execution of the background and refresh the page effect is the same.

In fact, this situation can also request a specific method on the page, as long as the use of the accompanying parameters to judge, you can "request" a specific method.

The following shows the use of two different methods to request two different pages, just excerpt the code, detailed code can be downloaded at the end of the article.

Front desk:

How to request a page directly  $ (function () {/   *   $.get (    "requestpage.aspx",    {"token": "Ajax"},    function ( Data) {    $ ("#dataShow"). Text (data);    }   ); */   $.ajax ({    type: "Post",    URL: "responsepage.aspx",    //data: "{' token ': ' Ajax '} ',// The use of this way is not able to pass parameters, you have to know the reason to tell AH.    data: "Token=ajax",    success:function (data) {     $ ("#dataShow"). Text (data);     }   );  })


protected void Page_Load (object sender, EventArgs e) {if (!this. IsPostBack) {  if (request["token"]?? ") = = "Ajax")  {   //The following can be placed within a method, and then the "token" tag to determine which method to execute.     Response.Write ("I am directly requesting the text returned by the ASPX page!") ");     Response.End ();  }  } }

The above request return value is either a string or datatype to text or HTML type.

What if you want the data returned by the request to be in XML or JSON format?

If the XML format, you need to add a sentence response.contenttype= "application/xml"; it is also important to note that the content in write must be a string that can be parsed into XML, such as "<my>123 </my> "Yes," 123 "is not possible because the returned information is responsexml equal to null. Such as:

Front desk:

$.ajax ({    type: "Post",    URL: "responsepage.aspx",    //data: "{' token ': ' Ajax '} ',//The parameter cannot be passed in this way, You have to know the reason to tell AH.    data: "Token=ajax",    //Do not need to specify ContentType, because after the specified return is the entire page of HTML, do not know why, ask the answer AH.    dataType: "xml",    success:function (data) {     alert (data);    },    error:function (d, c,e) {     alert (e);     }   );


If the returned response is XML, this must be set to Response.ContentType = "application/xml";//If the returned response is XML, the returned string must be an XML document format that can be parsed. Response.Write ("<my>123</my>"); Response.End ();

If it is in JSON format, the response.contenttype= "Application/json" in the background code is optional and does not affect the returned value. However, the value in Response.Write must be in JSON format, otherwise there will be invalid JSON format error.

Front desk:

$.ajax ({    type: "Post",    URL: "responsepage.aspx",    //data: "{' token ': ' Ajax '}",//data must be in the form of {key:value}) , this is a string and is not possible.    ///Data:{token: "Ajax"},//this way is also possible.    data: "Token=ajax",    //Do not need to specify ContentType, because jquery will automatically add contenttype= "Application/x-www-form-urlencode".    dataType: "JSON",    success:function (data) {     alert (data);    },    error:function (d, c,e) {     Alert (e);     }    });

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

The jquery document says that you can use the data request page in the form {Key:value}, when jquery automatically adds contenttype= "Application/x-www-form-urlencode" Causes the incoming data to be automatically converted to the Key=value form.


If the returned response is XML, this must be set to Response.ContentType = "Application/json";//If the returned response is XML, the returned string must be an XML document format that can be parsed. Response.Write ("[123]"); Response.End ();

2. Request the method in the background of the ASPX page.

In fact, the above direct Request page method also with the introduction of a request in-page method of the solution, that is, in the foreground of Ajax passed a parameter as a marker, such as the above "token", and then in the background of the Page_Load inside to determine the value of tokens, Different methods are performed depending on the value. The following is a direct execution of the method in the background of the page.

(1) When using the simple get or post method, the returned value is still the HTML content of the current page, even if the method requested is the one in the page, and the current page is the last requested, because ContentType and datatype cannot be set. Therefore, in the request method, the simple method is still inappropriate.

(2) When using a non-convenient method, either post or GET, if datatype is XML, text, HTM, the last value returned is still the content of the entire HTML page. So if you want to think of the value, or set datatype as "JSON" it, do not forget to set the ContentType as "Application/json;charset=utf-8", do not set this, JSON is not returned. It is also important to ensure that the requested method in the background is static, and that the [WebMethod] tag is still public.

Front desk:

$.ajax ({    type: "Post",    URL: "Requestpage.aspx/requestedmethod",    contentType: "Application/json; Charset=utf-8 ",    dataType:" JSON ",    success:function (res) {     alert (" Success: "+RES.D); Note that after you add a D to get the string information, as for why you want to add a D, you see through Chrome to return the response to know, O (∩_∩) o    },    error:function (XMLreq, err, c) {     Alert ("Error:" + err);    }   );


Background method that needs to be requested by Ajax [Webmethod][scriptmethod (Usehttpget=true)]//If you want to use a POST request, remove this flag public static string Requestedmethod () {return "[123]";}

It is no problem to use post directly:

If the type is changed to "get", an "500 internal error" appears. The error message is: {"message": "Attempt to invoke method ' Requestedmethod using GET request", but do not allow this.

The solution is to add a subscript to the post-method [Scriptmethod (Usehttpget=true)],scriptmethod Under System.Web.Script.Services. After that, you can request it in the foreground by get, but if you add this tag, the foreground will not be able to use post to request it.

3. Request a method in the background of the ASPX page with parameters

Front desk:

$.ajax ({    type: "Post",    URL: "Responsepage.aspx/requestmethod1",    data: "{' msg ': ' Hello '}",    ContentType: "Application/json;charset=utf-8",//This sentence can not be forgotten.    dataType: "JSON",    success:function (res) {     $ ("#dataShow"). Text ("Success:" + RES.D); Note that there is a D, as for why to see the response through Chrome, O (∩_∩) O.    },    error:function (XMLreq, err, c) {     $ ("#dataShow"). Text ("Error:" + err);    }   );


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

In general the way with parameters and without parameters, the difference is that when using the AJAX request, to pass a data parameter, note that the data must be a JSON-formatted string, otherwise it will be reported JSON error, specifically why, Because you pass the contenttype is Application/json AH.

Request for ASMX (WebService) condition

When requesting webservice, the main request is to ask for a method in WebService, and don't forget the hint of uncomment at the beginning of the code before the request "//to allow ASP. NET AJAX to invoke this Web service from a script, uncomment the downstream.

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

The methods in the request WebService are handled in a similar way to the request for the ASPX page background method, but there are some differences.

Features of the method requested in WebService:

(1) The requested method must be public.

(2) The method must have a [WebMethod] tag.

(3) If you want to request by using GET, there is also a [Scriptmethod (usehttpget=true)] flag. When using GET request WebService method, it is not enough to add this token, but also to modify the Web. config file, let WebService support get method request, otherwise "because the URL unexpectedly"/getxmlbyget "end, The request format is not recognized. "Error. To modify the method: Add the following red content under the system.web configuration section:

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

(4) When requesting XML data types, be aware that if the method returns a string type, the returned XML format is:

If the method returns a string, it wraps the returned string back in the <string> label.

For example, the following method is requested after the return value:

[Webmethod]public string Getxmlbypost () {return "I am requesting the returned XML by post";}

return value:

<?xml version= "1.0" encoding= "Utf-8"? ><string xmlns= "" > I was requested by post to return the xml</ String>

The red part is the string that is returned by the requested method, and the others are added automatically, so when you get the data through jquery in the foreground, it should be $ (res). Find ("string"). Text (); If the method returns a XmlDocument object, Is the XML object constructed in the method.

For example, the following method is requested after the return value:

Using the Get method to request XML, note that the returned string must be 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> I am requesting the returned XML by Get method </my> "; System.Xml.XmlDocument doc = new System.Xml.XmlDocument (); Doc. LOADXML (XML); return doc;}

The response returned is:

<?xml version=\ "1.0\" encoding=\ "utf-8\"?><my> I'm requesting a return by Get method xml</my>

You can now take the data through the way of $ (res). Find ("my"). Text (). At this point the operation is entirely your own constructed XML.

(5) About the request to return JSON note that the return is also the "[d:{}]" format of the data, when the foreground is obtained, you must add a ". D", the other and the XML is almost.

(6) The type of text is not much to say.

Request a ASHX case

The request ashx is similar to the situation that requests the APSX page directly, after all is through the response. Write (String) to return the data.

The place to note is: context. The value of Response.ContentType, which is differentiated according to the value of datatype:

Text: "Text/plain";

XML: "Application/xml";

JSON: "Application/json".

When datatype is XML, response. The string in the Write (string) must conform to the XML format, response for JSON. The string in the Write (string) must conform to the JSON format, otherwise a parse error will occur, which is the same as the ASPX page.

If you want to use the session, add the System.Web.SessionState reference to the handler code, and let the handler inherit the IRequiresSessionState interface, be sure to inherit the interface, or it will go wrong.

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: 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.