Use jquery Ajax to request WebService to achieve a more concise ajax_jquery

Source: Internet
Author: User

In the past, when we were doing Ajax, we had to use either a generic handler (. ashx) or a Web service (. asmx), and each request would have to build a file like this. It's a lot of trouble to build a bunch of ashx files.

Now we can use the WebMethod method to make the AJAX implementation more concise

1, if you want to use WebMethod, that must be a reference to the namespace.

Using System.Web.Services;

Here, for the convenience of development, I created a new page dedicated to writing WebMethod methods. That would be easier and better managed. If you have more AJAX requests, you can build a few more pages. Classify the request according to the name of the page
example, the following post the background code:

<summary> 
///Get Task name based on task ID, Task completion status, task quantity 
///</summary> 
///<param name= "id" > Task ID </param> 
///<returns></returns> 
[WebMethod] public 
static string Getmissioninfobyid (int id) 
{ 
Commonservice commonservice = new Commonservice (); 
DataTable table = Commonservice.getsysmissionbyid (ID); 
//..... 
Return "false"; 

This WebMethod method in the background requires a public static method, which takes note of the addition of the Wemethod attribute, and if you want to manipulate the session in this method. You have to add attributes to the method.

[WebMethod (EnableSession = True)]//or [WebMethod (true)] public 
static string Getmissioninfobyid (int id) 
{ 
Commonservice commonservice = new Commonservice (); 
DataTable table = Commonservice.getsysmissionbyid (ID); 
//..... 
Return "false"; 

2. Now that the WebMethod method has been written in the background. It's just a bad call. Use jquery here. More Concise

$.ajax ({ 
type: "POST", 
contentType: "Application/json", 
URL: "webmethodajax.aspx/ Getmissioninfobyid ", 
data:" {id:12} ", 
DataType:" JSON ", 
success:function () 
{ 
//callback after successful request   Processing. 
}, 
error:function () 
{ 
//callback processing when the request fails. 
} 

Here is a simple description of the Ajax several parameters of jquery, type: The types of requests, which must be post. WebMethod method only accepts post-type requests

ContentType: Content encoding type when sending information to the server. We must use Application/json here.

URL: The path of the requested server-side handler, in the form "filename (with suffix)/method name"

Data: Parameter list. Note that the parameter here must be a JSON-formatted string, remembering to be a string format, such as: "{aa:11,bb:22,cc:33, ...}".

If you're not writing a string, jquery will actually serialize it into a string, then the server-side is not JSON-formatted, and cannot be empty, even if there are no arguments written as "{}", as in the example above. A lot of people don't succeed, that's why.

DataType: The data type returned by the server. Must be JSON and none of the others are valid.  Because WebService is a JSON format that returns data in the form of: {"D": "..."}. Success: callback function after a successful request. You can do any processing of the returned data here.

We can see that some of the parameter values are fixed, so from the point of view of reusability, we can extend the jquery to a simple encapsulation of the above function: We build a script file called Jquery.extend.js. In the inside write a method called Ajaxwebservice (because WebMethod is actually webservice, so the method is valid for the request *.asmx), the code is as follows:

<summary> 
///jquery prototype extensions, encapsulating AJAX requests Webserveice 
///</summary> 
///<param name= "url" Type= "string" > processing the requested address </param> 
///<param name= "Datamap" type= "string" > Parameter, JSON-formatted string </param > 
///<param name= "fnsuccess" type= "function" > callback function after successful request </param> 
$.ajaxwebservice = function (URL, Datamap, fnsuccess) { 
$.ajax ({ 
type: POST), 
contentType: "Application/json", 
Url:url, 
Data:datamap, 
DataType: "JSON", 
success:fnsuccess 
}); 

OK, so we're going to ask the WebMethod method to call this:

 
 

The following is a package that was used to look at his package when I was with a manager. I think it's good.

First is to build a JS file, the filename with you up. I have built a commonajax.js inside two methods, look at the following code:

function Json2str (o) { 
var arr = []; 
var FMT = function (s) { 
if (typeof s = = ' object ' && s!= null) return json2str (s); 
Return/^ (String|number) $/.test (typeof s)? "" + S + "'": S; 
} 
for (var i in O) arr.push ("' + i +" ': "+ FMT (O[i])); 
Return ' {' + arr.join (', ') + '} '; 
} 
function Invoke (URL, param) { 
var result; 
$.ajax ({ 
type: POST, 
Url:url, 
async:false, 
data:json2str (param), 
contentType: " Application/json; Charset=utf-8 ", 
dataType:" JSON ", 
success:function (msg) {result 
= MSG.D; 
}, 
error: Function (R, S, E) { 
throw new Error (); 
} 
}); 
return result; 

Our call at the front desk is easier.

 
 

But if that's the way it is. You should pay attention to the background WebMethod method. The key of the JSON must be the same as the formal parameter of the WebMethod method, and the order of the parameters is not chaotic. Otherwise, the request fails.

For example, the backend method is as follows:

[WebMethod] 
public static string Getmissioninfobyid (int id,string name) 
{ 
// 
..... Return "false"; 

We want to pass two parameters, the format is as follows:

[CSharp] View plain copy print?

The above is a small series to introduce the use of jquery Ajax request WebService to achieve more concise Ajax, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

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.