zoukankan      html  css  js  c++  java
  • AJAX请求 $.get方法的使用

    使用jQuery的$.get方法可以以GET方式发起AJAX请求。$.get方法是jQuery的实用工具函数。

    get方法语法

    $.get(url,parameters,callback)

    参数

     

    url

    (字符串)服务器端资源地址。

    parameter

    (对象)需要传递到服务器端的参数。其形式为“键/值”。它会查询的字符串追加到url。

    callback

    (函数)在请求完成时被调用。该函数参数依次为响应体和状态。

    返回值

    XHR实例

    看个简单的例子

    客户端代码:

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <title></title>
    <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
    <script type="text/javascript">
    $().ready(function () {
      $('#selectNum').change(function () {
        var num = $(this).val();
        $.get('Server.aspx', { id: num }, function (text,status) { alert(text); });
      })
    })
    </script>
    </head>
    <body>
    <select id="selectNum">
      <option value="0">--select--</option>
      <option value="1">1</option>
      <option value="2">2</option>
      <option value="3">3</option>
    </select>
    </body>
    </html>
    

    服务端主要代码:

    protected void Page_Load(object sender, EventArgs e)
    {
      if (!Page.IsPostBack)
      {
        if (Request["id"] != null && !string.IsNullOrEmpty(Request["id"].ToString()))
        {
          Response.Write(GetData(Request["id"].ToString()));
        }
      }
    }
    
    protected string GetData(string id)
    {
      string str = string.Empty;
      switch (id)
      {
        case "1":
          str += "This is Number 1";
          break;
        case "2":
          str += "This is Number 2";
          break;
        case "3":
          str += "This is Number 3";
          break;
        default:
          str += "Warning Other Number!";
          break;
      }
      return str;
    }
    
    

    运行程序,结果如图:

    clip_image001

    用httpwatcher拦截请求信息,当下拉框中选择数字时,可以截取到如下请求信息。

    使用$.get方法时的截图:

    clip_image003

    从图中我们可以看到,参数id被追加到了url地址后面。

    $.get方法发起的是GET请求,这种请求大多用于查询某些信息。

    Demo下载

  • 相关阅读:
    Codeforces 985G. Team Players
    关于Hall定理的学习
    bzoj 4561: [JLoi2016]圆的异或并
    UOJ #188. 【UR #13】Sanrd
    LOJ #6053. 简单的函数
    Codeforces F. Cowmpany Cowmpensation
    POJ 3710:Matrix Power Series
    codeforces533E
    luogu2885
    codeforces722E
  • 原文地址:https://www.cnblogs.com/Johnny_Z/p/2552600.html
Copyright © 2011-2022 走看看