1. 程式人生 > >$.ajax與$.post/$.get方法的使用

$.ajax與$.post/$.get方法的使用

$.ajax


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title></title>
  </head>
  <body>
  <div id="form-div">
    <h1></h1>
    <form id="form1" onsubmit="return false" action="##" >
      <p>使用者名稱:<input name="userName" type="text" id="txtUserName" tabindex="1" size="15" value=""/> <span id="usemsg"></span></p>
      <p>密 碼:<input name="password" type="password" id="TextBox2" tabindex="2" size="16" value=""/></p>
      <p><input type="button" value="登入" onclick="login()">
    </form>
  </div>

  <script src="js/jquery-1.9.1.min.js"></script>
  <script type="text/javascript">
      function login() {
          //校驗資料
          if($("#txtUserName").val().length==0){
            $("#usemsg").text("使用者名稱不能為空").css("color:red");
          }
          var user = $("#txtUserName").val();
          var password = $("#TextBox2").val();
          var jsonStr = {"userName":user,"password":password};//object型別
          /*var jsonArrayFinal = JSON.stringify(jsonStr);//string型別*/
          $.ajax({
              /* post方法取值能否取到
             * application/x-www-form-urlencoded  能
             * multipart/form-data   不能
             * application/json   不能
             * */
              type:"post",
            /*  dataType:"json",*///從後臺返回資料型別
              url:"/servlet/TestServlet",

              contentType:"application/json;charset=utf-8", //傳送資訊至伺服器時內容編碼型別。
             /* data: $('#form1').serialize(),   //只能用get方法獲取*/
              data:jsonStr,
              beforeSend:function () {
                  //請求之前呼叫
                  //1,返回false可以取消本次ajax請求
                  //傳送完成之前之前執行函式
                  alert("before");
                  $("h1").html("資料處理中。。。");
              },
              complete:function (result) {
                  //3
                  alert("complete"+result);
                  $("h1").html("資料處理完畢。。。");
              },
              success:function (result) {
                  //頁面跳轉
                  //請求完成後呼叫
                  //2
                  //接收從後臺返回資料
                  alert("success"+JSON.stringify(result));
                  window.location.href="http://www.baidu.com";  //執行完所有ajax跳轉
              },
              error:function () {
                  //異常處理
                  alert("異常處理");
              }
          });

      }
  </script>
  </body>
</html>

$.post|$.get


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<div id="form-div">
    <h1></h1>
    <form id="form1" onsubmit="return false" action="##" >
        <p>使用者名稱:<input name="userName" type="text" id="txtUserName" tabindex="1" size="15" value=""/> <span id="usemsg"></span></p>
        <p>密 碼:<input name="password" type="password" id="TextBox2" tabindex="2" size="16" value=""/></p>
        <p><input type="button" id="button" value="登入">
    </form>
</div>


<script src="js/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
    $("#button").click(function () {
        alert("1");
        var user = $("#txtUserName").val();
        var password = $("#TextBox2").val();
        var jsonStr = {"userName":user,"password":password};//object型別
        /*$.post("/servlet/TestServlet",{"userName":user,"password":password},function () {
            alert("2");
            window.location.href = "http://www.baidu.com";
        });*/
        $.get("/servlet/TestServlet",{"userName":user,"password":password},function () {
            alert("2");
            window.location.href = "http://www.baidu.com";
        });
    })

</script>
</body>
</html>

後臺程式碼:

package com.myapp.servlet;

import com.sun.deploy.net.HttpRequest;

import javax.xml.ws.spi.http.HttpContext;
import java.io.IOException;
import java.io.PrintWriter;

public class TestServlet extends javax.servlet.http.HttpServlet {
    protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
        doGet(request,response);
    }

    protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {

        String userName =  request.getParameter("userName");
       String password = request.getParameter("password");


        System.out.println(userName);
        System.out.println(password);

        
        //json方式返回資料給前臺\"代表"
        String strJson = "{\"id\":\"123456\"}";
        PrintWriter out = response.getWriter();
        out.print(strJson);
    }
}

推薦參考:

https://blog.csdn.net/xcymorningsun/article/details/53019425?utm_source=blogxgwz2 https://blog.csdn.net/csdn_yudong/article/details/52537609?utm_source=blogxgwz0