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!

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 English version
Recommended: Win version, supports code prompts!

SublimeText3 Mac version
God-level code editing software (SublimeText3)