Ajax without jQuery
本问题已经有最佳答案,请猛点这里访问。
Possible Duplicate:
How to make an ajax call without jquery?
我在js(Ajax)中有代码,但我想在没有Ajax的情况下(XMLHttpRequest)
1 2 3 4 5 6 7 8 9 10 11 | $.ajax({ type:'POST', data:'slug='+prize, url:'/wybrana-nagroda/', success:function(msg) { $('#whaiting').hide(); if(msg==='winner') $(window.location).attr('href','/formularz'); } }); |
应该怎么样?
1 2 3 4 5 | function send(post, url) { var client = new XMLHttpRequest(); client.open("POST", url); client.send(message); } |
?
谢谢。
如果您希望它在所有浏览器上兼容,您需要执行以下操作:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | function sendRequest(url,callback,postData) { var req = createXMLHTTPObject(); if (!req) return; var method = (postData) ?"POST" :"GET"; req.open(method,url,true); req.setRequestHeader('User-Agent','XMLHTTP/1.0'); if (postData) req.setRequestHeader('Content-type','application/x-www-form-urlencoded'); req.onreadystatechange = function () { if (req.readyState != 4) return; if (req.status != 200 && req.status != 304) { // alert('HTTP error ' + req.status); return; } callback(req); } if (req.readyState == 4) return; req.send(postData); } var XMLHttpFactories = [ function () {return new XMLHttpRequest()}, function () {return new ActiveXObject("Msxml2.XMLHTTP")}, function () {return new ActiveXObject("Msxml3.XMLHTTP")}, function () {return new ActiveXObject("Microsoft.XMLHTTP")} ]; function createXMLHTTPObject() { var xmlhttp = false; for (var i=0;i<XMLHttpFactories.length;i++) { try { xmlhttp = XMLHttpFactories[i](); } catch (e) { continue; } break; } return xmlhttp; } |
图片来源:quirksmode