首先为大家分享了原生javascript实现ajax代码,供大家参考,具体内容如下
var getxmlhttprequest = function() { if (window.xmlhttprequest) { //主流浏览器提供了xmlhttprequest对象 return new xmlhttprequest(); } else if (window.activexobject) { //低版本的ie浏览器没有提供xmlhttprequest对象 //所以必须使用ie浏览器的特定实现activexobject return new activexobject(microsoft.xmlhttprequest); }};var xhr = getxmlhttprequest();xhr.onreadystatechange = function() { console.log(xhr.readystate); if (xhr.readystate === 3 && xhr.status === 200) { //获取成功后执行操作 //数据在xhr.responsetext console.log(xhr.responsetext); }};xhr.open(get, data.php, true);xhr.send();
下面和大家分享几种利用javascript实现原生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'); } } }
以上就是本文的全部内容,希望对大家的学习有所帮助。