使用Extjs,jquery,javascript进行ajax请求实例分析


通过阅读《疯狂Ajax讲义(第3版)——jQueryExt JSPrototypeDWR企业应用前端开发实战(含CD光盘1张)试读样章》,本文总结了使用Extjs,jquery,javascript进行ajax请求的方法。实际上,不论是使用extjs还是jquery,最终都是使用的javascript中的XMLHttpRequest对象。ajax请求的参数一般包括:请求方式(POST或GET),请求的URL,请求的参数,请求成功或失败时的回调函数。

ExtJS, 使用Ext.Ajax 类进行ajax请求。下面是一个例子:

点击(此处)折叠或打开

  1. Ext.Ajax.request({
  2.     url: 'ajax_demo/sample.json',//ajax请求的url
  3.     success: function(response, opts) {//当HTTP响应200 OK,就会调用success回调函数
  4.        var obj = Ext.decode(response.responseText);//decode http响应文本,一般是json字符串
  5.        console.dir(obj);
  6.     },
  7.     failure: function(response, opts) {//当请求失败,执行该回调函数
  8.        console.log('server-side failure with status code ' + response.status);
  9.     }
  10. });

Jquery中,使用函数$.ajax $.get $.post进行异步请求,下面是一个例子:

点击(此处)折叠或打开

  1. /* 以post方式请求,将响应的结果显示在id为result的div中 */
  2.     $.ajax({
  3.       url: "test.php",
  4.       type: "post",
  5.       data: values,
  6.       success: function(){
  7.           alert("success");
  8.            $("#result").html('submitted successfully');
  9.       },
  10.       error:function(){
  11.           alert("failure");
  12.           $("#result").html('there is error while submit');
  13.       } 
  14.     });


javascript方式,使用XMLHttpRequest对象进行ajax请求,下面是一个例子:
使用XMLHttpRequest对象发送请求的基本步骤如下:
创建一个XMLHttpRequest的引用
告诉XMLHttpRequest对象,哪个函数会处理XMLHttpRequest对象状态的改变,为此要设置onreadystatechange属性
指定请求的属性。open()
将请求发送给服务器。send()
xmlHttp.responseText将响应提供为一个串

点击(此处)折叠或打开

  1. var xmlHttp;
  2.    //创建一个XMLHttpRequest对象
  3.     function createXMLHttpRequest()
  4.     {
  5.       if(window.ActiveXObject)
  6.       {
  7.          xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
  8.       }
  9.       else if(window.XMLHttpRequest)
  10.       {
  11.         xmlHttp = new XMLHttpRequest();
  12.       }
  13.     }
  14.     
  15.     //开始一个请求
  16.     function startRequest()
  17.     {
  18.       createXMLHttpRequest();
  19.       xmlHttp.onreadystatechange = handleStateChange;
  20.       xmlHttp.open("GET","simpleResponse.xml",true);
  21.       xmlHttp.send(null);
  22.     }
  23.     
  24.     //当xmlHttp对象的内部状态发生变化时候,调用此处理函数
  25.     //一旦接受到相应(readyState为4)
  26.     function handleStateChange()
  27.     {
  28.       if(xmlHttp.readyState == 4)
  29.       {
  30.          if(xmlHttp.status == 200)
  31.          {
  32.            alert("The server replied with:"+xmlHttp.responseText);
  33.            document.getElementById("result").innerHTML = xmlHttp.responseText;
  34.          }
  35.       }
  36.     }

更多关于ajax的参考:http://blog.chinaunix.net/uid/21209537/sid-143571-list-1.html
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值