1

可能重复:
如何在没有 jquery 的情况下进行 ajax 调用?

我在 js(Ajax) 中有代码,但我想在没有 Ajax(XMLHttpRequest) 的情况下制作它

$.ajax({
            type:'POST',
            data:'slug='+prize,
            url:'/wybrana-nagroda/',
            success:function(msg)
            {
                $('#whaiting').hide();
                if(msg==='winner') 
                    $(window.location).attr('href','/formularz');
            }
        });

它应该是什么样子?

function send(post, url) {
  var client = new XMLHttpRequest();
  client.open("POST", url);
  client.send(message);
}

?

谢谢。

4

1 回答 1

2

如果您希望它在所有浏览器上兼容,则需要执行以下操作:

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;
}

信用:怪癖模式

于 2012-12-10T18:17:40.277 回答