Explanation on the use of JQuery Ajax in asp.net and calling background examples

伊谢尔伦
Release: 2017-01-16 17:44:26
Original
2263 people have browsed it

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.

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 to make a 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 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 " "123" is acceptable, but "123" is not acceptable because responseXml in the returned information is equal to null. As shown below:

Explanation on the use of JQuery Ajax in asp.net and calling background examples

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

Backend:

// If the returned response is xml, you must set it like this

Response.ContentType = "application/xml";
// If the returned response is xml, the returned string must be in an xml document format that can be parsed.
Response.Write("123");
Response.End();

If it is in json format, Response. ContentType="application/json" 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);  
       }
 });
Copy after login

Record: If you directly request a page, if the data uses the string form "{'token':'ajax'}", jquery will not be able to 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:

// If the returned response is xml, you must set it like this
Response.ContentType = "application/json";
// If it is returned The response is xml, and the returned string must be in an xml document format that can be parsed.
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, it must be ensured that the requested method in the background is static and marked with [webmethod], and it must also 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 using post directly:

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

解决方法就是在后方法上再加一个标[ScriptMethod(UseHttpGet=true)],ScriptMethod 在System.Web.Script.Services下.这样之后,就可以在前台通过Get方式请求了,但是如果加了这个标记之后,前台就不能用POST进行请求了。

3、 请求aspx页面后台中的方法,带参数

前台:

$.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);
      }
});
Copy after login

后台:

[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

返回值:

我是通过Post方式请求返回的xml

红色部分是被请求方法返回的字符串,其他是自动添加的,所以在前台中通过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

返回的响应为:

我是通过Get方式请求返回的xml

此时就可以通过$(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接口,一定要继承这个接口,否则会出错的。


下面来说明利用JQuery的$.ajax()可以很方便的调用asp.net的后台方法。

1、无参数的方法调用

asp.net 代码:

using System.Web.Script.Services;   
[WebMethod]   
public static string SayHello()   
{        
      return "Hello Ajax!";   
}  
using System.Web.Script.Services;
[WebMethod]
public static string SayHello()
{     
    return "Hello Ajax!";
}
Copy after login

注意:1.方法一定要静态方法,而且要有[WebMethod]的声明

JQuery 代码:

/// <reference path="jquery-1.4.2-vsdoc.js"/>   
$(function() {   
    $("#btnOK").click(function() {   
        $.ajax({   
            //要用post方式   
            type: "Post",   
            //方法所在页面和方法名   
            url: "data.aspx/SayHello",   
            contentType: "application/json; charset=utf-8",   
            dataType: "json",   
            success: function(data) {   
                //返回的数据用data.d获取内容   
                alert(data.d);   
            },   
            error: function(err) {   
                alert(err);   
            }   
        });   
        //禁用按钮的提交   
        return false;   
    });   
});  
/// <reference path="jquery-1.4.2-vsdoc.js"/>
$(function() {
    $("#btnOK").click(function() {
        $.ajax({
            //要用post方式
            type: "Post",
            //方法所在页面和方法名
            url: "data.aspx/SayHello",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(data) {
                //返回的数据用data.d获取内容
                alert(data.d);
            },
            error: function(err) {
                alert(err);
            }
        });
        //禁用按钮的提交
        return false;
    });
});
Copy after login

2、带参数的方法调用

asp.net 代码:

using System.Web.Script.Services;   
[WebMethod]   
public static string GetStr(string str, string str2)   
{   
    return str + str2;   
}  
using System.Web.Script.Services;
[WebMethod]
public static string GetStr(string str, string str2)
{
    return str + str2;
}
Copy after login

JQuery 代码:

/// <reference path="jquery-1.4.2-vsdoc.js"/>   
$(function() {   
    $("#btnOK").click(function() {   
        $.ajax({   
            type: "Post",   
            url: "data.aspx/GetStr",   
            //方法传参的写法一定要对,str为形参的名字,str2为第二个形参的名字   
            data: "{&#39;str&#39;:&#39;我是&#39;,&#39;str2&#39;:&#39;XXX&#39;}",   
            contentType: "application/json; charset=utf-8",   
            dataType: "json",   
            success: function(data) {   
                //返回的数据用data.d获取内容   
                  alert(data.d);   
            },   
            error: function(err) {   
                alert(err);   
            }   
        });   
        //禁用按钮的提交   
        return false;   
    });   
});  
/// <reference path="jquery-1.4.2-vsdoc.js"/>
$(function() {
    $("#btnOK").click(function() {
        $.ajax({
            type: "Post",
            url: "data.aspx/GetStr",
            //方法传参的写法一定要对,str为形参的名字,str2为第二个形参的名字
            data: "{&#39;str&#39;:&#39;我是&#39;,&#39;str2&#39;:&#39;XXX&#39;}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(data) {
                //返回的数据用data.d获取内容
                  alert(data.d);
            },
            error: function(err) {
                alert(err);
            }
        });
        //禁用按钮的提交
        return false;
    });
});
Copy after login

3、返回数组方法的调用

asp.net 代码:

using System.Web.Script.Services;   
[WebMethod]   
public static List<string> GetArray()   
{   
    List<string> li = new List<string>();   
    for (int i = 0; i < 10; i++)   
        li.Add(i + "");   
    return li;   
}  
using System.Web.Script.Services;
[WebMethod]
public static List<string> GetArray()
{
    List<string> li = new List<string>();
    for (int i = 0; i < 10; i++)
        li.Add(i + "");
    return li;
}
Copy after login

JQuery 代码:

/// <reference path="jquery-1.4.2-vsdoc.js"/>   
$(function() {   
    $("#btnOK").click(function() {   
        $.ajax({   
            type: "Post",   
            url: "data.aspx/GetArray",   
            contentType: "application/json; charset=utf-8",   
            dataType: "json",   
            success: function(data) {   
                //插入前先清空ul   
                $("#list").html("");   
                //递归获取数据   
                $(data.d).each(function() {   
                    //插入结果到li里面   
                    $("#list").append("<li>" + this + "</li>");   
                });   
                alert(data.d);   
            },   
            error: function(err) {   
                alert(err);   
            }   
        });   
        //禁用按钮的提交   
        return false;   
    });   
});  
/// <reference path="jquery-1.4.2-vsdoc.js"/>
$(function() {
    $("#btnOK").click(function() {
        $.ajax({
            type: "Post",
            url: "data.aspx/GetArray",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(data) {
                //插入前先清空ul
                $("#list").html("");
                //递归获取数据
                $(data.d).each(function() {
                    //插入结果到li里面
                    $("#list").append("<li>" + this + "</li>");
                });
                alert(data.d);
            },
            error: function(err) {
                alert(err);
            }
        });
        //禁用按钮的提交
        return false;
    });
});
Copy after login

4、返回Hashtable方法的调用
asp.net 代码:

using System.Web.Script.Services;   
using System.Collections;   
[WebMethod]   
public static Hashtable GetHash(string key,string value)   
{   
    Hashtable hs = new Hashtable();   
    hs.Add("www", "yahooooooo");   
    hs.Add(key, value);   
    return hs;   
}  
using System.Web.Script.Services;
using System.Collections;
[WebMethod]
public static Hashtable GetHash(string key,string value)
{
    Hashtable hs = new Hashtable();
    hs.Add("www", "yahooooooo");
    hs.Add(key, value);
    return hs;
}
Copy after login

JQuery 代码:

/// <reference path="jquery-1.4.2-vsdoc.js"/>   
$(function() {   
    $("#btnOK").click(function() {   
        $.ajax({   
            type: "Post",   
            url: "data.aspx/GetHash",   
            //记得加双引号  T_T   
            data: "{ &#39;key&#39;: &#39;haha&#39;, &#39;value&#39;: &#39;哈哈!&#39; }",   
            contentType: "application/json; charset=utf-8",   
            dataType: "json",   
            success: function(data) {   
                alert("key: haha ==> "+data.d["haha"]+"\n key: www ==> "+data.d["www"]);   
            },   
            error: function(err) {   
                alert(err + "err");   
            }   
        });   
        //禁用按钮的提交   
        return false;   
    });   
});  
/// <reference path="jquery-1.4.2-vsdoc.js"/>
$(function() {
    $("#btnOK").click(function() {
        $.ajax({
            type: "Post",
            url: "data.aspx/GetHash",
            //记得加双引号  T_T
            data: "{ &#39;key&#39;: &#39;haha&#39;, &#39;value&#39;: &#39;哈哈!&#39; }",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(data) {
                alert("key: haha ==> "+data.d["haha"]+"\n key: www ==> "+data.d["www"]);
            },
            error: function(err) {
                alert(err + "err");
            }
        });
        //禁用按钮的提交
        return false;
    });
});
Copy after login

5、操作xml
XMLtest.xml:

<?xml version="1.0" encoding="utf-8" ?>  
<data>  
  <item>  
    <id>1</id>  
    <name>qwe</name>  
  </item>  
  <item>  
    <id>2</id>  
    <name>asd</name>  
  </item>  
</data>  
<?xml version="1.0" encoding="utf-8" ?>
<data>
  <item>
    <id>1</id>
    <name>qwe</name>
  </item>
  <item>
    <id>2</id>
    <name>asd</name>
  </item>
</data>
Copy after login

JQuery 代码:

$(function() {   
    $("#btnOK").click(function() {   
        $.ajax({   
            url: "XMLtest.xml",   
            dataType: &#39;xml&#39;, //返回的类型为XML ,和前面的Json,不一样了   
            success: function(xml) {   
                //清空list   
                $("#list").html("");   
                //查找xml元素   KVM 网上购物 毛刷 网站建设 北京快递公司 超声波焊接机
                $(xml).find("data>item").each(function() {   
                    $("#list").append("<li>id:" + $(this).find("id").text() +"</li>");   
                    $("#list").append("<li>Name:"+ $(this).find("name").text() + "</li>");   
                })   
            },   
            error: function(result, status) { //如果没有上面的捕获出错会执行这里的回调函数   
                alert(status);   
            }   
        });   
        //禁用按钮的提交   
        return false;   
    });   
});  
$(function() {
    $("#btnOK").click(function() {
        $.ajax({
            url: "XMLtest.xml",
            dataType: &#39;xml&#39;, //返回的类型为XML ,和前面的Json,不一样了
            success: function(xml) {
                //清空list
                $("#list").html("");
                //查找xml元素
                $(xml).find("data>item").each(function() {
                    $("#list").append("<li>id:" + $(this).find("id").text() +"</li>");
                    $("#list").append("<li>Name:"+ $(this).find("name").text() + "</li>");
                })
            },
            error: function(result, status) { //如果没有上面的捕获出错会执行这里的回调函数
                alert(status);
            }
        });
        //禁用按钮的提交
        return false;
    });
});
Copy after login



Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template