Home >Web Front-end >JS Tutorial >Detailed explanation of JQuery Ajax usage summary in asp.net
Since the introduction of JQuery, the use of Ajax has become more and more convenient, but there are still some problems that can cause pain in a short period of time during use. 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 url The value of the parameter, accompanied by some marked parameters, is requested directly. 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(); } } }
The return values of the above requests are all strings, that is, the dataType is text or html.
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 " "d2a011ee392b74abe61e19d6296ea1e81233c1f76050803a65506838bd8f3a1544d" 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); } });
Backstage:
// 如果要是返回的响应为xml,则必须这样设置 Response.ContentType = "application/xml"; // 如果要是返回的响应为xml,返回的字符串必须是可以被解析的xml文档格式。 Response.Write("<my>123</my>"); Response.End();
If yes 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: "{'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); } });
Record: If you directly request a page, if the data uses the string form "{'token':'ajax'}", 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();
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); } });
Backstage:
// 需要被Ajax请求的后台方法 [WebMethod] [ScriptMethod(UseHttpGet=true)] // 如果要使用POST请求,去掉这个标记 public static string RequestedMethod() { return "[123]"; }
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:"{'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); } });
Backend:
[WebMethod] public static string RequestMethod1(string msg) { return msg; }
Generally speaking, The parameter method is similar to that without parameters. The difference is that when using ajax request, a data parameter must be passed. Note that the data must be a string in json format, otherwise a json error will be reported. The specific reason why is because you The contentType passed is application/json.
Requesting 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格式是这样的:
如果方法返回的是字符串,则会把返回的字符串包装在98c455a79ddfebb79781bff588e7b37e标签中返回。
比如以下方法请求后的返回值:
[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接口,一定要继承这个接口,否则会出错的。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持PHP中文网。
更多详解JQuery Ajax 在asp.net中使用总结相关文章请关注PHP中文网!