1. 程式人生 > >AJAX中的利用POST傳送資料

AJAX中的利用POST傳送資料


 

這裡我只寫關鍵語句,其它的就和GET方法一樣的,如果不請楚,請看我前面的文章:Ajax的JSP示例以及相關知識介紹,適合於入門者
function doMyPost()
{
    //這裡一定要加兩次編碼,具體原因請看:AJAX中利用POST方法向服務提交資料時亂碼的解決方案 
    var title=encodeURI(encodeURI(document.getElementById("title").value));
    var content=encodeURI(encodeURI(document.getElementById("content").value));
    var url="writeBlg.jsp";
    var postDate='title='+title+"&content="+content;
    httpRequest=createRequest();    
    httpRequest.open("POST",url,true);
    httpRequest.onreadystatechange=disContent;
    //設定傳送頭部
    httpRequest.setRequestHeader("content-length",postDate.length);    
    httpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
    httpRequest.send(postDate);
}
function disContent()
{
        if(httpRequest.readystate==4)
 {
  if(httpRequest.status==200)
  {
                        var response=httpRequest.responseText;
                        //這裡只能夠用indexOf方法,因為返還有一大堆HTML程式碼
                        //我被這個問題折磨了好幾十分鐘
                        if(response.indexOf("operateOK")>0)
                        {
                            document.getElementById("addButton").disabled=false;
                        }
                        var title=document.getElementById("title").value;
                        var content=document.getElementById("content").value;                        
   document.getElementById("totalContent").innerHTML+="<br>"+"title:"+title+"<br>"+"content:"+content;          
                        document.getElementById("title").value="";
                        document.getElementById("content").value="";
  }
  else
  {
   alert('Something Wrong has Happend!');
  }
 }