AJAX提交方法(POST)Demon


  AJAX的POST提交方法,本質上來看和GET差不多,有些細小的區別,POST要提交數據時,需要setRequestHeader()方法來提交HTTP頭,然后send()方法中提交數據(格式為:"?str=String&str2=String2");str和str2為變量名,String和String2為要發送的值。

  其他與Get差不多。

  下面是一個發送並接收username和password的Demon,先創建一個.html文件,名稱隨意,代碼如下:

  <body>
  <script type="text/javascript" src="1.js"></script>
    用戶名稱:<input type="text" id="username" /><br />
   用戶密碼:<input type="password" id="password" /><br />
 <input type="button" onclick="fun();" value="提交"> <br/>
 <p id="txt"></p>
  </body>

  接着來創建1.js的Javascript文件,要和.html在同一目錄下,代碼如下:

function fun(){
    if(window.XMLHttpRequest){
        xmlhttp = new XMLHttpRequest();
    }else if(window.ActiveXObject){
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }else{
        alert("對象無法被構建");
    }
    
    username = document.getElementById("username").value;
    password = document.getElementById("password").value;
    
    xmlhttp.onreadystatechange = handchange;
    xmlhttp.open("POST","Servlet1?username="+username+"&password="+password,true);
    xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");  //設置的HTTP頭
    xmlhttp.send("task=task&msg=msg");  //此處只是為了證明send()的使用方法,無意義
}

function handchange(){
    if(xmlhttp.readyState == 4){
        if(xmlhttp.status == 200){
            document.getElementById("txt").innerHTML = xmlhttp.responseText;
        }
    }else{
        document.getElementById("txt").innerHTML = "耐心等待...";
    }
}

  下面創建一個Servlet注意在web.xml里面的映射名稱要和xmlhttp.open("POST","Servlet1?username="+username+"&password="+password,true);此處的Servlet1一致。

  Servlet1,doPost代碼如下:

response.setContentType("text/html");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        String username = new String(request.getParameter("username").getBytes("ISO-8859-1"),"UTF-8");
        String password = new String(request.getParameter("password").getBytes("ISO-8859-1"),"UTF-8");
        String task = new String(request.getParameter("task").getBytes("ISO-8859-1"),"UTF-8");
        String msg = new String(request.getParameter("msg").getBytes("ISO-8859-1"),"UTF-8");
        
        System.out.println(username+""+password);
        if(task.equals("task")){
            if(msg.equals("msg")){
                out.println(username+""+password);//send()若是成功傳入了數據則,在.html也面中顯示輸入的值
            }
        }

  截圖如下:

輸入數據,點擊提交,截圖如下:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM