Home  >  Article  >  Web Front-end  >  Detailed explanation of jquery ajax definition and usage examples

Detailed explanation of jquery ajax definition and usage examples

伊谢尔伦
伊谢尔伦Original
2017-06-19 09:23:081059browse

Definition and Usage

The ajax() method loads remote data through HTTP requests.

This method is the underlying AJAX implementation of jQuery. For simple and easy-to-use high-level implementations, see $.get, $.post, etc. $.ajax() returns the XMLHttpRequest object it created. In most cases you will not need to manipulate this function directly unless you need to manipulate less commonly used options for more flexibility.

In the simplest case, $.ajax() can be used directly without any parameters.

Note: All options can be set globally through the $.ajaxSetup() function.

jQuery Ajax is very commonly used in web application development. It mainly includes common refresh-free operation methods such as ajax, get, post, load, getscript, etc. Let me introduce it to you.

Let’s start with the simplest method. When processing complex ajax requests, jQuery uses the jQuery.ajax() method. There are some simple methods in jQuery, which encapsulate the jQuery.ajax() method, so that we do not need to use the jQuery.ajax() method when processing some simple Ajaxevents, some of which The method has appeared in previous articles, I believe everyone will be able to master it soon.

Methods to perform general Ajax requests

1.load() Load remote data into the selected element

<script type="text/javascript">
$(document).ready(function(){
  $("#b01").click(function(){
  $(&#39;#myDiv&#39;).load(&#39;/jquery/test.txt&#39;);
  });
});
</script>

2.ajax() Load data into the XMLHttpRequest object

<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
  /// <summary>
  /// param1 param2 对应前面js传递来的参数。
  /// </summary>
  /// <param name="param1"></param>
  /// <param name="param2"></param>
  /// <returns></returns>
  [System.Web.Services.WebMethod]
  public static string GetDataTable(String param1, String param2)
  {
    return DataTable2Json(CreateDataTable(param1, param2));
  }
  public static System.Data.DataTable CreateDataTable(String param1, String param2)
  {
    System.Data.DataTable dataTable1 = new System.Data.DataTable("BlogUser");
    System.Data.DataRow dr;
    dataTable1.Columns.Add(new System.Data.DataColumn("UserId", typeof(System.Int32)));
    dataTable1.Columns.Add(new System.Data.DataColumn("UserName", typeof(System.String)));
    dataTable1.PrimaryKey = new System.Data.DataColumn[] { dataTable1.Columns["UserId"] };
    for (int i = 0; i < 8; i++)
    {
      dr = dataTable1.NewRow();
      dr[0] = i;
      dr[1] = "【孟子E章】" + i.ToString() + " 前端传递的参数的值分别是:" + param1 + ", " + param2;
      dataTable1.Rows.Add(dr);
    }
    return dataTable1;
  }
  public static string DataTable2Json(System.Data.DataTable dt)
  {
    StringBuilder jsonBuilder = new StringBuilder();
    jsonBuilder.Append("{\"");
    jsonBuilder.Append(dt.TableName.ToString());
    jsonBuilder.Append("\":[");
    for (int i = 0; i < dt.Rows.Count; i++)
    {
      jsonBuilder.Append("{");
      for (int j = 0; j < dt.Columns.Count; j++)
      {
        jsonBuilder.Append("\"");
        jsonBuilder.Append(dt.Columns[j].ColumnName);
        jsonBuilder.Append("\":\"");
        jsonBuilder.Append(dt.Rows[i][j].ToString());
        jsonBuilder.Append("\",");
      }
      jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
      jsonBuilder.Append("},");
    }
    jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
    jsonBuilder.Append("]");
    jsonBuilder.Append("}");
    return jsonBuilder.ToString();
  }  
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
  <title>jQuery Ajax 调用后台方法返回 DataSet 或者 DataTable 的例子</title>
  <script type="text/javascript" src="jquery-1.6.2.min.js"></script>
</head>
<body>
  <form id="form1" runat="server">
  <div id="result"></div>
  </form>
  <script type="text/javascript">
    $(document).ready(function () {
      $.ajax({
        type: "POST",
        url: "<%=Request.Url.ToString() %>/GetDataTable",  /* 注意后面的名字对应CS的方法名称 */
        data: "{\"param1\":\"8888\",\"param2\":\"参数2\"}", /* 注意参数的格式和名称 */
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (result) {
          data = jQuery.parseJSON(result.d);  /*这里是否解析要看后台返回的数据格式,如果不返回表名则无需要 parseJSON */
          t = "<table border=&#39;1&#39;>";
          $.each(data.BlogUser, function (i, item) { /* BlogUser是返回的表名 */
            t += "<tr>";
            t += "<td>" + item.UserId + "</td>";
            t += "<td>" + item.UserName + "</td>";
            t += "</tr>";
          })
          t += "</table>";
          $("#result").html(t);
        }
      });
    });      
  </script>
</body>
</html>

3.post() Pass parameters through post method

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>.NET下jQuery-post方法应用</title>
    <script src="js/jquery-1.3.2.min.js" type="text/javascript"></script>
</head>
<body>
    <div style="margin:15px; font-size:13px;">
        加法:
        <input type="text" id="txt_1" name="txt_1" maxlength="5" style="width:50px;" /> + 
        <input type="text" id="txt_2" name="txt_2" maxlength="5" style="width:50px;" /> 
        <input type="button" id="btn_1" value="计算" /> 
        <span id="span_1" style="color:Red; font-weight:bold; font-size:14px;">结果:</span>
        
        <br />
        
        乘法:
        <input type="text" id="txt_3" name="txt_3" maxlength="5" style="width:50px;" /> × 
        <input type="text" id="txt_4" name="txt_4" maxlength="5" style="width:50px;" /> 
        <input type="button" id="btn_2" value="计算" /> 
        <div id="div_2" style="color:Red; font-weight:bold; font-size:14px;">结果:</div>
    </div>
    
    <script type="text/javascript">
        $("#btn_1").click(function(){
            //验证
            if ($("#txt_1").val()==&#39;&#39; || $("#txt_2").val()==&#39;&#39;)
            {
                alert(&#39;请输入要计算的值&#39;);
                return false;
            }
            //向add.ashx请求结果
            $.post(&#39;Enumerate/add.ashx&#39;,{ 
                //参数一
                num1: $(&#39;#txt_1&#39;).val(), 
                //参数二
                num2: $("#txt_2").val() 
            }, 
            //回调函数
            function(theback) 
            {
                //输出结果
                $("#span_1").text(theback);
            },
            //返回类型
            "text"
            );
        });
        
        $("#btn_2").click(function(){
            //验证
            if ($("#txt_3").val()==&#39;&#39; || $("#txt_4").val()==&#39;&#39;)
            {
                alert(&#39;请输入要计算的值&#39;);
                return false;
            }
            //向multiply.ashx请求结果
            $.post(&#39;Enumerate/multiply.ashx&#39;,{ 
                //参数一
                num1: $(&#39;#txt_3&#39;).val(), 
                //参数二
                num2: $("#txt_4").val() 
            },
            //回调函数 
            function(theback) 
            {
                //输出结果
                $("#div_2").html(&#39;第一个数:&#39;+theback.num1+&#39;<br />&#39;+&#39;第二个数:&#39;+theback.num2+&#39;<br />&#39;+&#39;算法类型:&#39;+theback.type+&#39;<br />&#39;+&#39;计算结果:&#39;+theback.result);
            },
            //返回类型
            "json"
            );
        });
    </script>
</body>
</html>

4.get() Pass parameters through get method, use the same post() method

5.getScript () Request and execute a javascript file through Get method, url is the javascript file address

The above is the detailed content of Detailed explanation of jquery ajax definition and usage examples. For more information, please follow other related articles on the PHP Chinese website!

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