Jquery.ajax requests the similarities and differences between ASPX and ASHX Jquery Ajax calls aspx page method

Source: Internet
Author: User

1.jquery.ajax Request aspx

The static method of requesting ASPX should be aware of the problem:

(1) The back-end method of aspx must be static and add the WebMethod attribute

(2) in the Ajax method contenttype must be "Application/json",

(3) Data transmitted must be strict JSON data, such as "{' A ': ' AA ', ' B ': ' BB '}", and the parameters must correspond to the static method parameter one by one

(4) The default form of the data returned by the ASPX back-end method is "{' d ': ' Return content '}", so if datatype is specified as "JSON" it must be DATA.D to get the return data

The request method is defined in the Webfrom page (the method must be static and the WebMethod attribute must be added)

[Webmethod]public static string GetString (String str_a,string str_b) {    return str_a+str_b;}

Front page Request

$ (function () {$.jax ({      URL: ' default.aspx/getstring ',      type: ' Post ',      contentType: ' Application/json ',// This must indicate the encoding of the content to be passed to the server, and it must be JSON, otherwise the background method will not get the passed data.      dataType: ' json ',//The client reads the returned data in JSON      : ' {' str_a ': ' aaa ', ' str_b ': ' bbbb '} ',//The parameter must be the same as the parameter name in the background Data must be passed in JSON format      success:function (result) {              alert (RESULT.D);//Because the WebMethod method returns the data format by default in JSON format and data format such as: " {' d ': ' Returned data '} ', so go through. D to get the returned content.                              }     });});

2. Request Ashx

Note the problem:

(1) ContentType in AJAX methods if the specified must be specified as "application/x-www-form-urlencoded", the data is not obtained in ashx Request.Form

(2) If datatype is JSON and wants jquery to parse JSON data automatically, ASHX must return strict JSON data, and must be in the form of double quotation marks (which are reversed with antisense characters), such as: context. Response.Write ("{\" d\ ": \" "Hello world\"} "), or jquery will parse JSON failed.

(3) If because ContentType is not set or is not a "application/x-www-urlencoded" type, Reque.form gets no data and can obtain the requested content through Context.Request.InputStream.

(4) In the request ashx the data parameter has these forms: data:{' a ': ' AA ', ' B ': ' BB '}, Data: ' A=aa&b=bb ', data:{a: ' AA ', b: ' BB '}, These three kinds of data can be obtained by request.form["".

Jquery Ajax calls aspx page method

in ASP. NET WebForm development, there are several ways to use jquery Ajax to pass the value

1) Common play: Through the general processing procedures ASHX processing;

2) Advanced gameplay: Through the static method in the Aspx.cs +webmethod processing;

3) The art play: processing through WCF.

The first and third methods are beyond the scope of this article, and the second approach is highlighted below.

Description

In our impressions, ASP. NET Web services end with. asmx, and our current ASP. NET also implements WEB services because System.Web.Handlers.ScriptModule is already added to the default Web. config, which is used to manage Ajax in ASP. Functionality of the HTTP module, so that the request is processed by this handler, regardless of whether the user is requesting an. asmx file or an. aspx file.

Background code:
Using System.Web.Services; Introduce the namespace [webmethod]public static string SayHello () {    return "Hello ajax!";}
Front page code:
<button id= "BTN" > Submit </button>
JavaScript code:
$ (function () {         $ ("#btn"). Click (function () {             $.ajax ({                          type: "POST",//To use the post                             URL: "/demo.aspx/ SayHello ",//method on the page and method name            contentType:" Application/json; Charset=utf-8 ",                 dataType:" JSON ",                 success:function (data) {                                    alert (DATA.D);            error:function (ERR) {                     alert (err);                 }    );}     );

Effect:

Places to be aware of

I.. data parameter notation

1) Common notation, JSON key value pairs, such as: Single parameter data: "{newsID:" + ID + "}",//Multiple Parameter form: Data: "{newsID:" + NewsID + ", Name:" + name + "}",// 2) Literary writing: a variety of quotation marks, double quotes, single quotation marks, such as//single parameter notation: "{' Name ': '" + Name + "'}",//Multiple parameters: "Data:" {' content ': ' "+ $ (" #content "). Val () +" ' , ' createtime ': ' "+ $ (" #createTime "). Val () +" ', ' Creator ': ' "+ $ (" #creator "). Val () +" '} "//ERROR prone!!!!!

Second, the use of QueryString value is not the background to get the problem

In the WebMethod () method, the query string cannot be obtained by HTTPCONTEXT.CURRENT.QUERYSTRING.GET ("id"), because the WebMethod () is submitted by the Post method by default. It is not possible to take a value with getquerystring. The alternative is to use JS to get the parameters in the URL, using AJAX to submit to the background method is used:<script src= "/js/jquery-1.11.3.js" ></script>
< script type = "Text/javascript" >    function Getargs (strparame) {        var args = new Object ();        var query = location.search.substring (1); Get query string        var pairs = Query.split ("&");//break at Ampersand for        (var i = 0; i < pairs.length; I + +) {            var pos = pairs[i].indexof (' = ');//Look for "Name=value"            if (pos = =-1) continue;//If not found, skip
   
    var argname = pairs[i].substring (0, POS); Extract the name            var value = pairs[i].substring (pos + 1);//Extract the value            value = decodeuricomponent (value ); Decode it, if needed            args[argname] = value;//Store as a property        }        return args[strparame];//Return T He object} </script>
   

Three, the time question

A time format issue is returned when WCF or the impersonation Web service processes JSON. The workaround is as follows://messy time var rawdate = "/date (1347120000000+0800)/";//extract time string var strdate = Rawdate.substr (6, 13);// Convert the time string to type int var intdate = parseint (strdate);//Construct a Date object var newdate = new Date (intdate);//convert time to local time format var mydate = new Date.tolocaledatestring ();//end result alert (mydate);//Merge into a var resultdate = new Date (parseint ("/date") /". substr (6)). toLocaleDateString ();

Four, $.ajax parameter detailed

Standard notation: $.ajax ({     type: "Post",     DataType: "JSON",     contentType: "Application/json",//Note: WebMethod () This must be added, otherwise the client data will not be uploaded to the server     data:{as described above},//Note: The data parameter can be a string int type     URL: "List.aspx/deletenews",//Impersonation Web service, commit to method     //optional Async:false, blocking async is synchronous     beforesend:function () {          //do something.          Disabling buttons is generally prohibited, such as preventing users from repeating          the $ ("#btnClick"). attr ({disabled: "disabled"});          or display loading picture     },     success:function (data) {          alert ("Success:" + DATA.D);// Note here: You must pass DATA.D to obtain the value returned by the server          //service side can return the model directly, or return the serialized string, if necessary deserialization: string json = Json.parse (DATA.D);          Sometimes it is necessary to nest calls to Ajax requests, which is also possible     },     complete:function () {          //do something.          $ ("#btnClick"). Removeattr ("Disabled");          Hide loading Picture     },     error:function (data) {          alert ("Error:" + DATA.D);}     });

Jquery.ajax requests the similarities and differences between ASPX and ASHX jquery Ajax calls aspx page methods

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.