用AJAX的post方式与get方式


此处是原生态的js ajax技术,建议如果整站有使用jq的,采用jq的ajax方法会简便很多。
首先必须先获取浏览器的xmlhttp对象:

function getXmlHttpObject()
{
    var xmlHttp = null;
    try {
        xmlHttp = new XMLHttpRequest(); // code for IE7+, Firefox, Chrome, Opera, Safari
    }
    catch(e) {
        // Internet Explorer  if (window.XMLHttpRequest)
        try {
            xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
        } catch(e) {
            xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
    }
    return xmlHttp;
}

关于open和send的一点说明:

  • open(method, url, async)

规定请求的类型、URL以及是否异步处理请求。
method:请求的类型;GET或POST
url:文件在服务器上的位置
async:true(异步)或false(同步)

  • send(string)

将请求发送到服务器。
string:仅用于POST请求post方式:

function userAccountCheck1(doact, dovar)
{
    xmlHttp = getXmlHttpObject();
    if (xmlHttp == null || dovar == "") {
        return false;
    }
    var url = "./api/web/user.php?typ=" + doact + "&val=" + dovar;
    xmlHttp.onreadystatechange = stateChangedFunction;
    xmlHttp.open("GET", url, true);
    xmlHttp.send(null);
    return true;
}
function stateChangedFunction()
{
    //(xmlhttp.readyState==4 && xmlhttp.status==200)
    if (xmlHttp.readyState == 4 || xmlHttp.readyState == "complete")
    {
        document.getElementById("myDiv").innerHTML = xmlHttp.responseText;
    }
}

get方式:

function userAccountCheck2(doact, dovar)
{
    xmlHttp = getXmlHttpObject();
    if (xmlHttp == null || dovar == "") {
        return false;
    }
    var url = "./api/web/user.php?typ=" + doact + "&val=" + dovar;
    xmlHttp.onreadystatechange = stateChangedFunction;
    xmlhttp.open("POST", url, true);
    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlhttp.send(null);
    return true;
}
function stateChangedFunction()
{
    //(xmlhttp.readyState==4 && xmlhttp.status==200)
    if (xmlHttp.readyState == 4 || xmlHttp.readyState == "complete")
    {
        document.getElementById("myDiv").innerHTML = xmlHttp.responseText;
    }
}

原文链接:https://blog.yongit.com/note/87024.html