日期:2014-05-16  浏览次数:20786 次

ajax利用servlet发送请求,不用form中的action=...
如果数据处理不改变数据模型的状态,理论上采用GET方法,获取数据时应用GET方法。如果因为存储、更新数据,或者发送电子邮件,操作改变了数据模型的状态,应该使用POST方法。

  使用httpxmlrequest请求的话,将使用javascript创建查询串,来提交请求。使用GET发送请求send(null)。POST:send(...)。而不再用form的GET/POST,这样浏览器的url部分也不会出现。。?.....&....&...一连串的东西了。。。。

  例子:getAndPostExample.html:

<html>
<head>
<title>Sending Request Data Using GET and POST</title>

<script type="text/javascript">
   var xmlHttp;

function createXMLHttpRequest() {//创建xmlhttprequest对象。
    if (window.ActiveXObject) {
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    else if (window.XMLHttpRequest) {
        xmlHttp = new XMLHttpRequest();
    }
}
   
function createQueryString() {//创建查询串
    var firstName = document.getElementById("firstName").value;
    var middleName = document.getElementById("middleName").value;
    var birthday = document.getElementById("birthday").value;   
    var queryString = "firstName=" + firstName + "&middleName=" + middleName
        + "&birthday=" + birthday;
     return queryString;
}

function doRequestUsingGET() {//Get的主js
    createXMLHttpRequest();   
    var queryString = "GetAndPostExample?";
    queryString = queryString + createQueryString()
        + "&timeStamp=" + new Date().getTime();
    xmlHttp.onreadystatechange = handleStateChange;
    xmlHttp.open("GET", queryString, true);
   xmlHttp.send(null);
}

function doRequestUsingPOST() {//POST的主js
    createXMLHttpRequest();   
    var url = "GetAndPostExample?timeStamp=" + new Date().getTime();
   var queryString = createQueryString();   
    xmlHttp.open("POST", url, true);
    xmlHttp.onreadystatechange = handleStateChange;
    xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); //这句话不能去,否则得不到数据。确保服务器知道请求体中有参数。
   xmlHttp.send(queryString);
}
   
function handleStateChange() {
    if(xmlHttp.readyState == 4) {
        if(xmlHttp.status == 200) {
            parseResults();
        }
    }
}

function parseResults() {
    var responseDiv = document.getElementById("serverResponse");
    if(responseDiv.hasChildNodes()) {
        responseDiv.removeChild(responseDiv.childNodes[0]);
    }
   
    var responseText = document.createTextNode(xmlHttp.responseText);
    responseDiv.appendChild(responseText);
    }

</script>
</head>

<body>
<h1>Enter your first name, middle name, and birthday:</h1>

<table>
    <tbody>
        <tr>
            <td>First name:</td>
            <td><input type="text" id="first