Home Web Front-end JS Tutorial Use jQuery Ajax to request webservice to implement more concise Ajax

Use jQuery Ajax to request webservice to implement more concise Ajax

Jan 24, 2017 am 09:34 AM

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:

1

2

3

4

5

6

7

8

9

10

11

12

13

/// <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";

}

Copy after login

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

1

2

3

4

5

6

7

8

[WebMethod(EnableSession = true)]//或[WebMethod(true)]

public static string GetMissionInfoById(int id)

{

CommonService commonService = new CommonService();

DataTable table = commonService.GetSysMissionById(id);

    //.....

return "false";

}

Copy after login

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

$.ajax({

type: "POST",

contentType: "application/json",

url: "WebMethodAjax.aspx/GetMissionInfoById",

data: "{id:12}",

dataType: "json",

success: function()

   {

     //请求成功后的回调处理.

   },

   error:function()

{

//请求失败时的回调处理.

}

});

Copy after login

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:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

///<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

});

}

Copy after login

Okay, so we can call the webmethod method like this:

1

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

Copy after login

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:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

function json2str(o) {

var arr = [];

var fmt = function(s) {

if (typeof s == &#39;object&#39; && s != null) return json2str(s);

return /^(string|number)$/.test(typeof s) ? "&#39;" + s + "&#39;" : s;

}

for (var i in o) arr.push("&#39;" + i + "&#39;:" + fmt(o[i]));

return &#39;{&#39; + arr.join(&#39;,&#39;) + &#39;}&#39;;

}

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;

}

Copy after login


Our call in the foreground is relatively simple.

1

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

Copy after login

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:

1

2

3

4

5

6

[WebMethod]

public static string GetMissionInfoById(int Id,string name)

{

   //..... 

return "false";

}

Copy after login

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

1

2

[csharp] view plain copy print?

{"Id":23,"name":"study"}

Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

How to implement panel drag and drop adjustment function similar to VSCode in front-end development? How to implement panel drag and drop adjustment function similar to VSCode in front-end development? Apr 04, 2025 pm 02:06 PM

Explore the implementation of panel drag and drop adjustment function similar to VSCode in the front-end. In front-end development, how to implement VSCode similar to VSCode...

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

See all articles