Chinaunix首页 | 论坛 | 博客
  • 博客访问: 627118
  • 博文数量: 37
  • 博客积分: 106
  • 博客等级: 民兵
  • 技术积分: 993
  • 用 户 组: 普通用户
  • 注册时间: 2012-03-30 18:26
个人简介

来自汉江北邻的IT男一枚,专注于PHP和C#开发... 最常更新的技术Blog → https://enjoy233.cnblogs.com/

文章分类

全部博文(37)

文章存档

2013年(36)

2012年(1)

我的朋友

分类: JavaScript

2013-04-19 07:48:04

通过阅读《疯狂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




阅读(1582) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~