Use jQuery Ajax to request webservice to achieve a more concise Ajax

  • 2021-07-09 06:36:36
  • OfStack

In the past, when we were doing ajax, we had to rely on a general handler (. ashx) or web service (. asmx), and every one request had to build one such file. It is troublesome to build a lot of ashx files, and it looks uncomfortable.

Now we can use the webMethod method to make ajax more concise

1. Since you want to use WebMethod, you must refer to the namespace under 1

using System.Web.Services;

Here, for the convenience of development, I created a new page specifically for writing WebMethod method. That will be more convenient, but also better management. If ajax request more, you can build several pages. According to the name of the page to make the classification of the request
For example, post the background code below:


/// <summary> 
///  According to the task ID Get the task name , Task completion status , Number of tasks  
/// </summary> 
/// <param name="id"> Mission 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, and the WeMethod attribute should be added to the method; If you want to operate 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. Since the background WebMethod method has been written. Just call. Here on the use of JQuery. More concise


$.ajax({ 
type: "POST", 
contentType: "application/json", 
url: "WebMethodAjax.aspx/GetMissionInfoById", 
data: "{id:12}", 
dataType: "json", 
success: function() 
     { 
         // Callback processing after successful request . 
     }, 
     error:function() 
{ 
// Callback handling when a request fails . 
} 
}); 

Here to Jquery Ajax several parameters to do a simple description, type: Request type, here must use post. The WebMethod method only accepts post type requests

contentType: Content encoding type when sending information to server. We must use application/json here

url: Path to the requested server-side handler in the format "File name (with suffix)/method name"

data: Parameter list. Note that Parameter 1 here must be a string in json format, and remember that it is in string format, such as: "{aa: 11, bb: 22, cc: 33,...}".

If you don't write a string, jquery will actually serialize it into a string, so what you receive on the server side is not json format, and it can't be empty, even if there are no parameters, it should be written as "{}", as in the above example. That's why many people don't succeed.

dataType: The data type returned by the server. Must be json, nothing else is valid. Because webservice returns data in 1json format, it is in the form: {"d": "......"}. success: Callback function after successful request. You can do any processing of the returned data here.

We can see that some parameter values are fixed, so from the perspective of reusability, we can extend jquery and simply encapsulate the above functions: we build a script file called jquery. extend. js. Write a method called ajaxWebService (because webmethod is actually WebService, so the method is also valid for the request *. asmx). The code is as follows:


///<summary> 
///jQuery Prototype extension, re-encapsulation Ajax Request WebServeice 
///</summary> 
///<param name="url" type="String"> Address for processing requests </param> 
///<param name="dataMap" type="String"> Parameters, json Format 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 
}); 
} 

All right, so we request the webmethod method and we can call it like this:


$.ajaxWebService("WebMethodAjax.aspx/GetMissionInfoById", "{id:12}", function(result) {//......}); 

Below again paste a kind of package, is before with 1 manager, look at his package. Think it's not bad

First of all is also to build an js file, file name with you up. I built here an CommonAjax. js inside the two methods, see 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 in the foreground is relatively simple.


var result = Invoke("WebMethodAjax.aspx/GetMissionInfoById", { "name": arguments.Value, "id": id }); 

However, if this is the case. In the background WebMethod method to pass the parameters to note 1. key Json method must be the same as WebMethod method parameter 1, and the order of parameters should not be disordered. Otherwise, the request will fail.

For example, the background method is as follows:


[WebMethod] 
public static string GetMissionInfoById(int Id,string name) 
{ 
           //.....    
return "false"; 
} 

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


[csharp] view plain copy print?
{"Id":23,"name":"study"} 

Related articles: