Ajax异步获取前台信息

来源:互联网 发布:优化的南洋金珠会掉色 编辑:程序博客网 时间:2024/06/06 05:37

AJAX

AJAX = Asynchronous JavaScript and XML(异步的 JavaScript 和 XML)。

AJAX 不是新的编程语言,而是一种使用现有标准的新方法。

AJAX 是与服务器交换数据并更新部分网页的艺术,在不重新加载整个页面的情况下。

主要分四个步骤

第一步,创建xmlhttprequest对象,var xmlhttp =new XMLHttpRequest();XMLHttpRequest对象用来和服务器交换数据。

var xmlHttp;//本函数用来实例化xmlHttp对象function createHttpRequest(){if(window.ActiveXObject){//本方法适用于IE5,IE6等低版本的浏览器生成对象,当然现在很少有人用这种方法。xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");}else if(window.XMLHttpRequest){//适用于当前大部分版本的浏览器xmlHttp = new XMLHttpRequest();}}


第二步,使用xmlhttprequest对象的open()和send()方法发送资源请求给服务器。

xmlhttp.open(method,url,async) method包括get 和post,url主要是文件或资源的路径,async参数为true(代表异步)或者false(代表同步)

xhttp.send();使用get方法发送请求到服务器。

xhttp.send(string);使用post方法发送请求到服务器。

post 发送请求什么时候能够使用呢?

(1)更新一个文件或者数据库的时候。

(2)发送大量数据到服务器,因为post请求没有字符限制。

(3)发送用户输入的加密数据。


function startGet(){createHttpRequest();var url="Request.jsp?timeTemp"+new Date().getTime();xmlHttp.open("Get", url+"&"+createQueryString());xmlHttp.send(null);xmlHttp.onreadystatechange = processor;}function startPost(){createHttpRequest();var url="Request.jsp?timeTemp"+new Date().getTime();xmlHttp.open("Post", url);xmlHttp.setRequestHeader("content-Type", "application/x-www-form-urlencoded");xmlHttp.send(createQueryString());xmlHttp.onreadystatechange = processor;}

第三步,使用xmlhttprequest对象的responseText或responseXML属性获得服务器的响应。



0 0
原创粉丝点击