In the past, when we were doing ajax, we had to resort to general processing programs (.ashx) or web services (.asmx), and each request had to create such a file. In this way, we created a lot of ashx files, It’s more troublesome, and it doesn’t look good if it’s too much.
Now we can use the webMethod method to make the ajax implementation more concise
1. Since you want to use WebMethod, then definitely It is indispensable to reference the namespace
using System.Web.Services;
Here, for the convenience of development, I created a new page specifically for writing WebMethod methods. That will be more convenient, It is also easier to manage. If there are many ajax requests, you can create a few more pages. Classify the requests according to the name of the page.
For example, the background code is posted below:
/// <summary> /// 根据任务ID获取任务名称,任务完成状态,任务数量 /// </summary> /// <param name="id">任务ID</param> /// <returns></returns> [WebMethod] public static string GetMissionInfoById(int id) { CommonService commonService = new CommonService(); DataTable table = commonService.GetSysMissionById(id); //..... return "false"; }
The WebMethod method in the background is required to be a public static method, and the WeMethod attribute must be added to the method; if you want to operate the Session in this method, you must add attributes to the method
[WebMethod(EnableSession = true)]//或[WebMethod(true)] public static string GetMissionInfoById(int id) { CommonService commonService = new CommonService(); DataTable table = commonService.GetSysMissionById(id); //..... return "false"; }
2. Now that the background WebMethod methods have been written, we just need to call them. Let’s use JQuery here. It’s more concise
$.ajax({ type: "POST", contentType: "application/json", url: "WebMethodAjax.aspx/GetMissionInfoById", data: "{id:12}", dataType: "json", success: function() { //请求成功后的回调处理. }, error:function() { //请求失败时的回调处理. } });
Here A brief explanation of several parameters of Jquery's Ajax, type: the type of request, post must be used here. The 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 to the requested server-side handler, 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 be in string format, such as: "{aa:11,bb:22,cc:33, ...}".
If what you write is not a string, jquery will actually serialize it into a string, so what is received on the server side is not in json format and cannot be empty, even if there are no parameters. It should be written as "{}", as in the above example. Many people fail, and this is why.
dataType: The data type returned by the server. It must be json, anything else is invalid. Because the webservice returns data in json format, its form is: {"d":"...."}. Success: callback function after the request is successful. You can do whatever you want with the returned data here.
We can see that some of the parameter values are fixed, so from the perspective of reusability, we can make an extension for jquery and make a simple encapsulation of the above function: We build A script file is called jquery.extend.js. Write a method called ajaxWebService inside (because webmethod is actually WebService, so this method is also valid for requesting *.asmx). The code is as follows:
///<summary> ///jQuery原型扩展,重新封装Ajax请求WebServeice ///</summary> ///<param name="url" type="String">处理请求的地址</param> ///<param name="dataMap" type="String">参数,json格式的字符串</param> ///<param name="fnSuccess" type="Function">请求成功后的回调函数</param> $.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 like this:
$.ajaxWebService("WebMethodAjax.aspx/GetMissionInfoById", "{id:12}", function(result) {//......});
Here is another encapsulation, which is the encapsulation I saw with a manager before. I think it is pretty good.
First of all, create a js file. The file name is up to you. I have created two methods in CommonAjax.js here. 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 in the foreground is relatively simple.
var result = Invoke("WebMethodAjax.aspx/GetMissionInfoById", { "name": arguments.Value, "id": id });
But if we use this method, we should pay attention when passing parameters to the background WebMethod method. One point. The key of Json must be the same as the formal parameters of the WebMethod method, and the order of the parameters cannot be messed up. 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 need to pass two parameters, the format is as follows:
[csharp] view plain copy print? {"Id":23,"name":"study"}
The above is the editor’s introduction to using Jquery Ajax to request webservice to implement more concise Ajax. I hope it will be useful to you. Everyone is helpful. If you have any questions, please leave me a message and the editor will reply to you in time. I would also like to thank you all for your support of the PHP Chinese website!
For more articles related to using jQuery Ajax to request webservice to achieve more concise Ajax, please pay attention to the PHP Chinese website!