• AJAX请求 $.post方法的使用


    使用jQuery的$.post方法可以以POST形式向服务器发起AJAX请求。$.post方法是jQuery的实用工具方法。

    $.post方法语法

    $.post(url,parameters,callback)

    参数

     

    url

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

    parameter

    (对象)需要传递到服务器端的参数。 参数形式为“键/值”。

    callback

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

    返回值

    XHR实例

    看个简单的例子

    客户端代码:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    <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 idValue = $(this).val();
        //采用POST方式调用服务
        $.post('Server.aspx', { id: idValue }, 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>

    服务端主要代码:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    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拦截请求信息,当下拉框中选择数字时,可以截取到如下请求信息。

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

    clip_image003

    通过上图我们可以看到在POST Data里面有参数,说明这是一次POST请求。

    在服务器端状态有改变,或者是修改更新某些数据时多用POST请求。

    Demo下载

  • 相关阅读:
    工作之余
    用MFC如何高效地绘图
    C++运算符优先级
    CentOS5.9下用Kate
    3G门户网(3G.cn) 招聘 软件测试工程师
    深圳市东润信息咨询有限公司招聘职位: 3G无线产品经理
    广州杰赛科技股份有限公司 招聘 技术中心3G协议软件工程师
    3G门户网(3G.cn) 招聘 手机游戏开发工程师
    3G门户网(3G.cn) 招聘 技术支持工程师
    3G工程师:三大热门的3G职业资格培训认证
  • 原文地址:https://www.cnblogs.com/BrokenIce/p/5243412.html
Copyright © 2020-2023  润新知