用javascript实现ajax

经常用jquery,都快忘记怎么用javascript实现ajax了。在这里记录一下。

function getXhr() {
    var xhr = false;
    if (window.XMLHttpRequest) {
        try {
            xhr = new XMLHttpRequest();
        } catch(e) {
            xhr = false;
        }
    } else if (window.ActiveXObject) {
        try {
            xhr = new ActiveXObject('Msxml2.XMLHTTP');
        } catch(e) {
            try {
                xhr = new ActiveXObject('Microsoft.XMLHTTP');
            } catch(e) {
                xhr = false;
            }
        }
    }
    return xhr;
}

function sendajax(method) {
    var xhr = getXhr();
    if (xhr) {
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 4 && xhr.status == 200) {
                alert(xhr.responseText);
            }
        };
        if (method == "POST") {
            xhr.open('POST', "http://localhost:3000/dashboard/ajaxtest?t2=test2", true);
            xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
            xhr.send('t1=test1');
        }
        else if (method == "GET") {
            xhr.open('GET', "http://localhost:3000/dashboard/ajaxtest?t1=test1&t2=test2", true);
            xhr.send(null);
        }
    }
}

如果网站有跨域提交限制,使用POST方法时要加上相应的参数。

如,在rails中,加上

<%=request_forgery_protection_token.to_s%>=<%=form_authenticity_token.to_s%>
原文地址:https://www.cnblogs.com/zycjwdss/p/2157976.html