欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2022-04-15 17:47:21
...

$.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