AjaxDemo

原生JS實現Ajaxjavascript

function fun() {
        var xmlhttp;
        if (window.XMLHttpRequest) {
            //  IE7+, Firefox, Chrome, Opera, Safari 瀏覽器執行代碼
            xmlhttp = new XMLHttpRequest();
        } else {
            // IE6, IE5 瀏覽器執行代碼
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }

        xmlhttp.open("GET", "ajaxServlet?username=tom", true);

        xmlhttp.send();

        //當xmlhttp對象的就緒狀態改變是,觸發onreadystatechange
        xmlhttp.onreadystatechange = function() {
            //  x 判斷readyState就緒狀態是否爲4,判斷status想要狀態嗎是否爲200
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                //x  獲取服務器的響應結果
                var responseText = xmlhttp.responseText;
                
                alert(responseText);
            }
        }

    }

Jquery實現Ajax的第一種方式:css

function fun() {

         $.ajax({
            url:"ajaxServlet",
            type:"POST",
            data:{"username":"tom","age":25},
            success:function(data){
                alert(data);
            },
            error:function(){
                alert("出錯了")
            },
            dataType:"JSON"
        }); 
}

Jquery實現Ajax的第二種方式:html

function fun() {

  $.get("ajaxServlet",{username:"rose"},function(data){
            alert(data)
        },"text");
}

Jquery實現Ajax的第三種方式:java

function fun() {

  $.post("ajaxServlet",{username:"rose"},function(data){
            alert(data)
        },"text");
}

 

簡單案例:註冊校驗用戶名jquery

regist.htmlweb

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="js/jquery-3.4.1.min.js"></script>

<script>
    $(function() {
        $("#username").blur(function() {
            var username = $(this).val();
            $.get("findUserServlet", {username : username}, function(data) {
                var span = $("#u_username")
                if (data.userExsit) {
                    // username存在
                    span.css("color", "red")
                    span.html(data.msg)
                } else {
                    // username不存在
                    span.css("color", "green")
                    span.html(data.msg)
                }
            }); //$.get()能夠指定第四個參數爲dataType :json
        })
    })
</script>

</head>


<body>

    <form>
        <input type="text" placeholder="請輸入用戶名" id="username" name="username">
        <span id="u_username"></span> <br> 
        <input type="password" placeholder="請輸入密碼" name="password"><br> 
        <input type="submit" value="註冊">
    </form>

</body>
</html>

 

findUserServletajax

package com.infosys.web;
import java.io.IOException;
import java.util.HashMap;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.fasterxml.jackson.databind.ObjectMapper;

@WebServlet("/findUserServlet")
public class FindUserServler extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
     //指定瀏覽器解析的數據格式,不指定瀏覽器會將響應數據看成字符串處理,也會出現亂碼的現象。 //也能夠在發送Ajax請求裏指定一下datatype的類型爲Json
     response.setContentType("application/json;charset=utf-8"); 
        // 獲取用戶名
        String username = request.getParameter("username");
// 調用service層判斷用戶是否存在 (此處是直接模擬的數據,真實開發確定是查詢數據庫) HashMap<String,Object> map = new HashMap<String,Object>(); if("tom".equals(username)) { map.put("userExsit",true); map.put("msg","用戶名太受歡迎,請更換一個"); }else { map.put("userExsit",false); map.put("msg","用戶名可用"); } ObjectMapper mapper = new ObjectMapper(); // 將數據傳遞給客戶端 mapper.writeValue(response.getWriter(), map); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
相關文章
相關標籤/搜索