Home Backend Development C#.Net Tutorial Summary of usage related to using JQuery Ajax in asp.net

Summary of usage related to using JQuery Ajax in asp.net

Aug 16, 2017 pm 02:20 PM
ajax asp.net jquery

This article mainly introduces a detailed summary of the use of JQuery Ajax in asp.net. The editor thinks it is quite good, so I will share it with you now and give it as a reference. Let’s follow the editor and take a look.

Since the introduction of JQuery, the use of Ajax has become more and more convenient, but there will still be more or less painful problems in the use in a short period of time. . This article temporarily summarizes some issues that should be paid attention to when using JQuery Ajax. If there are any inappropriate or imperfect areas, you are welcome to correct and add.

This article will discuss the three methods of Ajax request aspx, ashx and asmx.

First look at the situation of requesting aspx

Ajax requests for Aspx pages can be made in two ways:

1. By using the get or post method , pass the page address as the value of the url parameter, and attach some tag parameters for direct request. This method of Ajax is hailed as "fake Ajax" by some people. On the surface, the page is not refreshed. In fact, the background execution and the effect of refreshing the page are the same.

In fact, in this case, you can also request a specific method in the page. As long as you use the attached parameters to judge, you can "request" a specific method.

The following shows the situation of using two different methods to request two different pages. Only the code is excerpted. The specific detailed code can be downloaded at the end of the article.

Front desk:


// 直接请求页面的方式
  $(function () {
   /*
   $.get(
    "RequestPage.aspx",
    { "token": "ajax" },
    function (data) {
    $("#dataShow").text(data);
    }
   );*/
   $.ajax({
    type:"Post",
    url: "ResponsePage.aspx",
    // data: "{'token':'ajax'}",// 使用这种方式竟然无法传递参数,各位有知道原因的告诉一下啊。
    data:"token=ajax",
    success: function (data) {
     $("#dataShow").text(data); 
    }
   });
  })
Copy after login

Backend:


##

protected void Page_Load(object sender, EventArgs e)
{
 if (!this.IsPostBack)
 {
  if ((Request["token"]??"")=="ajax")
  {
   // 下面这些内从可以放在一个方法里,然后通过“token”标记去判断执行哪个方法。
     Response.Write("我是直接请求aspx页面返回的文字!");
     Response.End();
  }
  }
 }
Copy after login

The above request return values ​​are all strings That is, the dataType is text or html type.

What should I do if I want the data returned by the request to be in xml or json format?

If it is in xml format, you need to add a Response.ContentType="application/xml"; another thing to note is that the content in Write must be a string that can be parsed into xml, such as " "123" is acceptable, but "123" is not acceptable because responseXml in the returned information is equal to null. As shown below:

Front desk:


 $.ajax({

    type: "Post",
    url: "ResponsePage.aspx",
    // data: "{'token':'ajax'}",// 使用这种方式竟然无法传递参数,各位有知道原因的告诉一下啊。
    data: "token=ajax",
    // 不需要指定contentType,因为指定后返回的是整个页面的html,不知道为啥,请求解答啊。
    dataType: "xml",
    success: function (data) {
     alert(data);
    },
    error: function (d, c,e) {
     alert(e); 
    }
   });
Copy after login

Backstage:


 // 如果要是返回的响应为xml,则必须这样设置

Response.ContentType = "application/xml";
// 如果要是返回的响应为xml,返回的字符串必须是可以被解析的xml文档格式。
Response.Write("<my>123</my>");
Response.End();
Copy after login

If it is in json format, the sentence Response.ContentType="application/json" in the background code is optional and does not affect the returned value. But the value in Response.Write must be in json format, otherwise there will be an Invalid Json format error.

Front desk:


$.ajax({
    type: "Post",
    url: "ResponsePage.aspx",
    // data: "{&#39;token&#39;:&#39;ajax&#39;}",// data必须是一个{key:value}的形式,这是一个字符串,是不行的。

    // data:{token:"ajax"},// 这种方式也可行。
    data: "token=ajax",
    // 不需要指定contentType,因为jquery会自动添加contentType=“application/x-www-form-urlencode”。
    dataType: "json",
    success: function (data) {
     alert(data);
    },
    error: function (d, c,e) {
     alert(e); 
    }

 
   });
Copy after login

Record: If you directly request a page, if the data uses a string like "{'token':'ajax'}" form, jquery cannot be converted to the form of token=ajax.

The jquery document says that you can use data in the form of {key: value} to request the page. At this time, jquery will automatically add contentType="application/x-www-form-urlencode" so that the incoming data will automatically Convert to key=value form.

Backend:


// 如果要是返回的响应为xml,则必须这样设置
Response.ContentType = "application/json";
// 如果要是返回的响应为xml,返回的字符串必须是可以被解析的xml文档格式。
Response.Write(“[123]");

Response.End();
Copy after login

2. Request the method in the aspx page background.

In fact, the above method of directly requesting the page also introduces a solution to the method of requesting the page, which is to pass a parameter as a tag in the ajax at the front desk, such as the "token" above, Then the value of the token is judged in the page_load in the background, and different methods are executed according to the different values. What we will introduce below is the method of directly executing the page background.

(1) When using the simple get or post method, since contentType and dataType cannot be set, even if the method in the page is requested, the final request is still the current page, and the returned value is still the html content of the current page. . So when requesting a method, the simple method is still inappropriate.

(2) When using non-convenient methods, whether it is post or get, if the dataType is xml, text, or htm, the final returned value is still the content of the entire html page. So if you want to think of the value, you should set the dataType to "json". Don't forget to set the contentType to "application/json;charset=utf-8". If you don't set this, json will not be returned. Moreover, you must also ensure that the requested method in the background is static, has a [webmethod] tag, and must be public.

Front desk:


 $.ajax({

    type: "post",
    url: "RequestPage.aspx/RequestedMethod",
    contentType: "application/json;charset=utf-8",
    dataType: "json",
    success: function (res) {
     alert("success:"+res.d); // 注意这点后面要加个d才能获取字符串信息,至于为什么要加个d,你通过chrome看看返回的响应就知道了,O(∩_∩)O
    },
    error: function (xmlReq, err, c) {
     alert("error:" + err);    }
   });
Copy after login

Backstage:


// 需要被Ajax请求的后台方法
[WebMethod]
[ScriptMethod(UseHttpGet=true)] // 如果要使用POST请求,去掉这个标记
public static string RequestedMethod()
{
 return "[123]";

}
Copy after login

There is no problem in using post directly:

If type is changed to "get", "500 Internal Error" will occur. The error message is: {"Message":"An attempt was made to use a GET request to call the method "RequestedMethod", but this is not allowed.

The solution is to add a flag to the last method [ScriptMethod(UseHttpGet=true) ], ScriptMethod is under System.Web.Script.Services. After this, you can request it through Get method in the front desk, but if you add this tag, the front desk cannot use POST to request it.

3 , Request the method in the background of the aspx page, with parameters

Front desk:


 $.ajax({
    type: "Post",
    url: "ResponsePage.aspx/RequestMethod1",
    data:"{&#39;msg&#39;:&#39;hello&#39;}",
    contentType: "application/json;charset=utf-8",// 这句可不要忘了。
    dataType: "json",
    success: function (res) {
     $("#dataShow").text("success:" + res.d); // 注意有个d,至于为什么通过chrome看响应吧,O(∩_∩)O。
    },
    error: function (xmlReq, err, c) {
     $("#dataShow").text("error:" + err);
    }
   });
Copy after login

Background:


[WebMethod]
public static string RequestMethod1(string msg)
{
  return msg;
 }
Copy after login

总体上带参数的方式和不带参数类似,不同点就是在使用ajax请求的时候,要传递一个data参数,注意这个data一定是一个json格式的字符串,否则就会报json错误的,具体为什么,因为你传递的contentType是application/json啊。

请求asmx(webservice)的情况

请求webservice的时候,主要是请求webservice中的方法,在请求之前不要忘记了代码开头的那段取消注释的提示“// 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。

// [System.Web.Script.Services.ScriptService]”

请求webservice中的方法的处理方式和请求aspx页面后台方法的处理方式类似,但也有一些不同。

被请求的webservice中方法的特点:

(1) 请求的方法必须是为public的。

(2) 方法必须有[WebMethod]标记。

(3) 如果想使用Get的方式请求,还要有[ScriptMethod(UseHttpGet=true)]标记。使用Get请求Webservice的方法的时候,只添加这个标记是不够的,还要修改Web.Config文件,让WebService支持Get方式请求,否则会出现 “因 URL 意外地以“/GetXmlByGet”结束,请求格式无法识别。“的错误。修改方法为:在System.web配置节下添加以下红色的内容:


<System.web>
……………
<webServices>
  <protocols>
  <add name="HttpGet"/>
  <add name="HttpPost"/>
  </protocols>
 </webServices>

</System.web>
Copy after login

(4) 请求xml数据类型的时候,要注意,如果方法返回的是string类型的,返回的xml格式是这样的:

如果方法返回的是字符串,则会把返回的字符串包装在标签中返回。

比如以下方法请求后的返回值:


 [WebMethod]

public string GetXmlByPost()
{
 return "我是通过Post方式请求返回的xml ";
}
Copy after login

返回值:


<?xml version="1.0" encoding="utf-8"?>

<string xmlns="http://tempuri.org/">我是通过Post方式请求返回的xml</string>
Copy after login

红色部分是被请求方法返回的字符串,其他是自动添加的,所以在前台中通过jquery获取数据的时候,应该$(res).find(”string”).text();如果方法返回的是xmlDocument对象,则就是方法中构造的xml对象。

比如以下方法请求后的返回值:


// 使用Get方式请求xml,注意返回的字符串一定要是可以解析的xml格式。
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public System.Xml. XmlDocument GetXmlByGet()
{
 string xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?><my>我是通过Get方式请求返回的xml</my>";
 System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
 doc.LoadXml(xml);
 return doc;

}
Copy after login

返回的响应为:


<?xml version=\"1.0\" encoding=\"utf-8\"?><my>我是通过Get方式请求返回的xml</my>
Copy after login

此时就可以通过$(res).find(”my”).text()的方式取数据了。此时操作的完全是你自己构造的xml。

 (5)   关于请求返回JSON需要注意的就是,返回的也是“[d:{}]”格式的数据,所在前台获取的时候,一定要加个”.d”,其他的和xml差不多了。

(6)    Text的类型的就不多说了。

请求ashx的情况

 请求ashx的时候和直接请求apsx页的情况类似,毕竟都是通过response.Write(string)的方式返回数据的。

  需要注意的地方是:context.Response.ContentType的值,根据dataType的值区分:

Text:“text/plain“;

XML:“application/xml“;

JSON:“application/json“.

dataType为xml的时候,response.Write(string)中的字符串一定要符合xml的格式,为json的时候,response.Write(string)中的字符串一定要符合json的格式为否则会出现解析错误,这个和aspx页是一样的。

如果要使用session的话,在handler的代码中添加System.Web.SessionState的引用,并让这个handler继承IRequiresSessionState接口,一定要继承这个接口,否则会出错的。

The above is the detailed content of Summary of usage related to using JQuery Ajax in asp.net. For more information, please follow other related articles on 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)

How to use PUT request method in jQuery? How to use PUT request method in jQuery? Feb 28, 2024 pm 03:12 PM

How to use PUT request method in jQuery? In jQuery, the method of sending a PUT request is similar to sending other types of requests, but you need to pay attention to some details and parameter settings. PUT requests are typically used to update resources, such as updating data in a database or updating files on the server. The following is a specific code example using the PUT request method in jQuery. First, make sure you include the jQuery library file, then you can send a PUT request via: $.ajax({u

PHP and Ajax: Building an autocomplete suggestion engine PHP and Ajax: Building an autocomplete suggestion engine Jun 02, 2024 pm 08:39 PM

Build an autocomplete suggestion engine using PHP and Ajax: Server-side script: handles Ajax requests and returns suggestions (autocomplete.php). Client script: Send Ajax request and display suggestions (autocomplete.js). Practical case: Include script in HTML page and specify search-input element identifier.

How to get variables from PHP method using Ajax? How to get variables from PHP method using Ajax? Mar 09, 2024 pm 05:36 PM

Using Ajax to obtain variables from PHP methods is a common scenario in web development. Through Ajax, the page can be dynamically obtained without refreshing the data. In this article, we will introduce how to use Ajax to get variables from PHP methods, and provide specific code examples. First, we need to write a PHP file to handle the Ajax request and return the required variables. Here is sample code for a simple PHP file getData.php:

jQuery Tips: Quickly modify the text of all a tags on the page jQuery Tips: Quickly modify the text of all a tags on the page Feb 28, 2024 pm 09:06 PM

Title: jQuery Tips: Quickly modify the text of all a tags on the page In web development, we often need to modify and operate elements on the page. When using jQuery, sometimes you need to modify the text content of all a tags in the page at once, which can save time and energy. The following will introduce how to use jQuery to quickly modify the text of all a tags on the page, and give specific code examples. First, we need to introduce the jQuery library file and ensure that the following code is introduced into the page: &lt

Use jQuery to modify the text content of all a tags Use jQuery to modify the text content of all a tags Feb 28, 2024 pm 05:42 PM

Title: Use jQuery to modify the text content of all a tags. jQuery is a popular JavaScript library that is widely used to handle DOM operations. In web development, we often encounter the need to modify the text content of the link tag (a tag) on ​​the page. This article will explain how to use jQuery to achieve this goal, and provide specific code examples. First, we need to introduce the jQuery library into the page. Add the following code in the HTML file:

PHP vs. Ajax: Solutions for creating dynamically loaded content PHP vs. Ajax: Solutions for creating dynamically loaded content Jun 06, 2024 pm 01:12 PM

Ajax (Asynchronous JavaScript and XML) allows adding dynamic content without reloading the page. Using PHP and Ajax, you can dynamically load a product list: HTML creates a page with a container element, and the Ajax request adds the data to that element after loading it. JavaScript uses Ajax to send a request to the server through XMLHttpRequest to obtain product data in JSON format from the server. PHP uses MySQL to query product data from the database and encode it into JSON format. JavaScript parses the JSON data and displays it in the page container. Clicking the button triggers an Ajax request to load the product list.

Understand the role and application scenarios of eq in jQuery Understand the role and application scenarios of eq in jQuery Feb 28, 2024 pm 01:15 PM

jQuery is a popular JavaScript library that is widely used to handle DOM manipulation and event handling in web pages. In jQuery, the eq() method is used to select elements at a specified index position. The specific usage and application scenarios are as follows. In jQuery, the eq() method selects the element at a specified index position. Index positions start counting from 0, i.e. the index of the first element is 0, the index of the second element is 1, and so on. The syntax of the eq() method is as follows: $("s

How to tell if a jQuery element has a specific attribute? How to tell if a jQuery element has a specific attribute? Feb 29, 2024 am 09:03 AM

How to tell if a jQuery element has a specific attribute? When using jQuery to operate DOM elements, you often encounter situations where you need to determine whether an element has a specific attribute. In this case, we can easily implement this function with the help of the methods provided by jQuery. The following will introduce two commonly used methods to determine whether a jQuery element has specific attributes, and attach specific code examples. Method 1: Use the attr() method and typeof operator // to determine whether the element has a specific attribute

See all articles