Summary of usage related to using JQuery Ajax in asp.net
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); } }); })
Backend:
##
protected void Page_Load(object sender, EventArgs e) { if (!this.IsPostBack) { if ((Request["token"]??"")=="ajax") { // 下面这些内从可以放在一个方法里,然后通过“token”标记去判断执行哪个方法。 Response.Write("我是直接请求aspx页面返回的文字!"); Response.End(); } } }
$.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); } });
// 如果要是返回的响应为xml,则必须这样设置 Response.ContentType = "application/xml"; // 如果要是返回的响应为xml,返回的字符串必须是可以被解析的xml文档格式。 Response.Write("<my>123</my>"); Response.End();
$.ajax({ type: "Post", url: "ResponsePage.aspx", // data: "{'token':'ajax'}",// 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); } });
// 如果要是返回的响应为xml,则必须这样设置 Response.ContentType = "application/json"; // 如果要是返回的响应为xml,返回的字符串必须是可以被解析的xml文档格式。 Response.Write(“[123]"); Response.End();
$.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); } });
// 需要被Ajax请求的后台方法 [WebMethod] [ScriptMethod(UseHttpGet=true)] // 如果要使用POST请求,去掉这个标记 public static string RequestedMethod() { return "[123]"; }
$.ajax({ type: "Post", url: "ResponsePage.aspx/RequestMethod1", data:"{'msg':'hello'}", 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); } });
[WebMethod] public static string RequestMethod1(string msg) { return msg; }
总体上带参数的方式和不带参数类似,不同点就是在使用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>
(4) 请求xml数据类型的时候,要注意,如果方法返回的是string类型的,返回的xml格式是这样的:
如果方法返回的是字符串,则会把返回的字符串包装在
比如以下方法请求后的返回值:
[WebMethod] public string GetXmlByPost() { return "我是通过Post方式请求返回的xml "; }
返回值:
<?xml version="1.0" encoding="utf-8"?> <string xmlns="http://tempuri.org/">我是通过Post方式请求返回的xml</string>
红色部分是被请求方法返回的字符串,其他是自动添加的,所以在前台中通过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; }
返回的响应为:
<?xml version=\"1.0\" encoding=\"utf-8\"?><my>我是通过Get方式请求返回的xml</my>
此时就可以通过$(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!

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

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

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

Hot Topics



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

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.

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:

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

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:

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.

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