In the past, when we were doing ajax, we had to use the general processing program (. ashx) or web services (. asmx), and every request must create such a file, which is very troublesome. Next we will get rid of ashx and asmx to use jQueryAjax to request webservice for more concise Ajax, for more information about ajax (. ashx) or web services (. asmx), and each request must create such a file. creating a large number of ashx files in this way is troublesome, And it looks uncomfortable if there are more files.
Now we can use the webMethod method to make ajax implementation more concise
1. Since WebMethod is used, you must reference the namespace.
Using System. Web. Services;
Here, for the convenience of development, I have created a page specifically used to write the WebMethod method. it will be convenient and easy to manage. if there are many ajax requests, you can create several more pages. classify requests by PAGE name
For example, the following is the background code:
////// Obtain the Task Name, task completion status, and task Quantity Based on the task ID //////Task ID///
[WebMethod] public static string GetMissionInfoById (int id) {CommonService commonService = new CommonService (); DataTable table = commonService. getSysMissionById (id );//..... return "false ";}
The WebMethod in the background must be a public static method. You must add the WeMethod attribute to the method. To operate the Session in the method, you must add the attribute 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 all the WebMethod methods in the background have been written, the call is delayed. Use JQuery here. It is 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 processing when the request fails .}});
Here, we will briefly describe the Ajax parameters of Jquery. type: Request type, which must be post. The WebMethod only accepts post requests.
ContentType: Content Encoding type when the message is sent to the server. Here we must use application/json
Url: the path of the server-side processing program of the request, in the format of "file name (including suffix)/method name"
Data: parameter list. Note that the parameters here must be strings in json format. Remember to use the string format, for example, "{aa: 11, bb: 22, cc: 33 ,...}".
If you do not write a string, jquery will actually serialize it into a string, so what the server receives is not in json format and cannot be blank, "{}" should be written even if no parameters are available, as shown in the preceding example. This is why many people fail.
DataType: Data Type returned by the server. It must be json, and none of the others is valid. Because webservice returns data in json format, the format is {"d ":"......."}. Success: the callback function after the request is successful. You can perform any processing on the returned data here.
We can see that some of the parameter values are fixed. Therefore, from the perspective of reusability, we can make an extension for jquery and make a simple encapsulation of the above function: let's create a script file named jquery. extend. js. Write a method named ajaxWebService in it (because webmethod is actually a WebService, the method is also valid for the request *. asmx). The Code is as follows:
////// JQuery prototype extension, re-encapsulate Ajax request WebServeice //////Request address///Parameter, a string in json format///Callback Function after successful request$. AjaxWebService = function (url, dataMap, fnSuccess) {$. ajax ({type: "POST", contentType: "application/json", url: url, data: dataMap, dataType: "json", success: fnSuccess });}
Okay, so we can call the webmethod method as follows:
$.ajaxWebService("WebMethodAjax.aspx/GetMissionInfoById", "{id:12}", function(result) {//......});
Next I will post another encapsulation. It is the encapsulation that I used to look at when I talked to a manager. I think it is not bad.
First, create a js file. The file name starts with you. Here I create two methods in CommonAjax. js. 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 at the front-end is relatively simple.
var result = Invoke("WebMethodAjax.aspx/GetMissionInfoById", { "name": arguments.Value, "id": id });
However, if this method is used. note the following when passing parameters to the WebMethod method in the background. the Json key must be the same as the form parameter of the WebMethod method, and the order of parameters cannot be changed. otherwise, the request fails.
For example, the background method is as follows:
[WebMethod]public static string GetMissionInfoById(int Id,string name){ //..... return "false";}
We need to pass two parameters, the format is as follows:
[csharp] view plain copy print?{"Id":23,"name":"study"}
The above section describes how to use Jquery Ajax to request webservice for more concise Ajax. I hope it will help you. If you have any questions, please leave a message, the editor will reply to you in a timely manner. I would like to thank you for your support for PHP chinnet!
For more information about how to use jQuery Ajax to request webservice to implement more concise Ajax, see the PHP Chinese website!