通过阅读《疯狂Ajax讲义(第3版)——jQueryExt JSPrototypeDWR企业应用前端开发实战(含CD光盘1张)试读样章》,本文总结了使用Extjs,jquery,javascript进行ajax请求的方法。实际上,不论是使用extjs还是jquery,最终都是使用的javascript中的XMLHttpRequest对象。ajax请求的参数一般包括:请求方式(POST或GET),请求的URL,请求的参数,请求成功或失败时的回调函数。
ExtJS, 使用Ext.Ajax 类进行ajax请求。下面是一个例子:
Jquery中,使用函数$.ajax $.get $.post进行异步请求,下面是一个例子:
javascript方式,使用XMLHttpRequest对象进行ajax请求,下面是一个例子:
使用XMLHttpRequest对象发送请求的基本步骤如下:
创建一个XMLHttpRequest的引用
告诉XMLHttpRequest对象,哪个函数会处理XMLHttpRequest对象状态的改变,为此要设置onreadystatechange属性
指定请求的属性。open()
将请求发送给服务器。send()
xmlHttp.responseText将响应提供为一个串
更多关于ajax的参考:http://blog.chinaunix.net/uid/21209537/sid-143571-list-1.html
ExtJS, 使用Ext.Ajax 类进行ajax请求。下面是一个例子:
点击(此处)折叠或打开
- Ext.Ajax.request({
- url: 'ajax_demo/sample.json',//ajax请求的url
- success: function(response, opts) {//当HTTP响应200 OK,就会调用success回调函数
- var obj = Ext.decode(response.responseText);//decode http响应文本,一般是json字符串
- console.dir(obj);
- },
- failure: function(response, opts) {//当请求失败,执行该回调函数
- console.log('server-side failure with status code ' + response.status);
- }
- });
Jquery中,使用函数$.ajax $.get $.post进行异步请求,下面是一个例子:
点击(此处)折叠或打开
- /* 以post方式请求,将响应的结果显示在id为result的div中 */
- $.ajax({
- url: "test.php",
- type: "post",
- data: values,
- success: function(){
- alert("success");
- $("#result").html('submitted successfully');
- },
- error:function(){
- alert("failure");
- $("#result").html('there is error while submit');
- }
- });
javascript方式,使用XMLHttpRequest对象进行ajax请求,下面是一个例子:
使用XMLHttpRequest对象发送请求的基本步骤如下:
创建一个XMLHttpRequest的引用
告诉XMLHttpRequest对象,哪个函数会处理XMLHttpRequest对象状态的改变,为此要设置onreadystatechange属性
指定请求的属性。open()
将请求发送给服务器。send()
xmlHttp.responseText将响应提供为一个串
点击(此处)折叠或打开
- var xmlHttp;
- //创建一个XMLHttpRequest对象
- function createXMLHttpRequest()
- {
- if(window.ActiveXObject)
- {
- xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
- }
- else if(window.XMLHttpRequest)
- {
- xmlHttp = new XMLHttpRequest();
- }
- }
-
- //开始一个请求
- function startRequest()
- {
- createXMLHttpRequest();
- xmlHttp.onreadystatechange = handleStateChange;
- xmlHttp.open("GET","simpleResponse.xml",true);
- xmlHttp.send(null);
- }
-
- //当xmlHttp对象的内部状态发生变化时候,调用此处理函数
- //一旦接受到相应(readyState为4)
- function handleStateChange()
- {
- if(xmlHttp.readyState == 4)
- {
- if(xmlHttp.status == 200)
- {
- alert("The server replied with:"+xmlHttp.responseText);
- document.getElementById("result").innerHTML = xmlHttp.responseText;
- }
- }
- }
更多关于ajax的参考:http://blog.chinaunix.net/uid/21209537/sid-143571-list-1.html