Heim  >  Artikel  >  Web-Frontend  >  使用JavaScript实现ajax的实例代码_javascript技巧

使用JavaScript实现ajax的实例代码_javascript技巧

WBOY
WBOYOriginal
2016-05-19 10:42:44973Durchsuche

AJAX = Asynchronous JavaScript and XML.

AJAX 是一种创建快速动态网页的技术。

AJAX 通过在后台与服务器交换少量数据的方式,允许网页进行异步更新。这意味着有可能在不重载整个页面的情况下,对网页的一部分进行更新。

实现ajax之前必须要创建一个 XMLHttpRequest 对象。如果不支持创建该对象的浏览器,则需要创建 ActiveXObject.具体方法如下:

var xmlHttp; 
function createxmlHttpRequest()
{ 
if (window.ActiveXObject) { 
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); 
} 
else if 
(window.XMLHttpRequest)
{ 
xmlHttp=new XMLHttpRequest(); 
} 
} 

(1)下面使用上面创建的xmlHttp实现最简单的ajax get请求:

function doGet(url)
{ 
// 注意在传参数值的时候最好使用encodeURI处理一下,以防出现乱码 
createxmlHttpRequest(); 
xmlHttp.open("GET",url); 
xmlHttp.send(null); 
xmlHttp.onreadystatechange = function()
{ 
if ((xmlHttp.readyState == 4) && (xmlHttp.status == 200)) { 
alert('success'); 
} 
else 
{ 
alert('fail'); 
} 
} 
} 

(2)使用上面创建的xmlHttp实现最简单的ajax post请求:

function doPost(url,data)
{ 
// 注意在传参数值的时候最好使用encodeURI处理一下,以防出现乱码 
createxmlHttpRequest(); 
xmlHttp.open("POST",url); 
xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); 
xmlHttp.send(data); 
xmlHttp.onreadystatechange = function() 
{ 
if ((xmlHttp.readyState == 4) && (xmlHttp.status == 200)) 
{ 
alert('success'); 
}
else
{ 
alert('fail'); 
} 
} 
} 

以上内容是小编给大家介绍的JavaScript实现ajax的实例代码,希望对大家有所帮助,在使用过程发现有任何疑问欢迎给我留言,小编会及时回复大家的。在此小编非常感谢大家对脚本之家网站的支持,相信我们会做的更好!

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn