日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

XMLHttpRequest對象的Get請求和Post請求的用法

作者:南瓜骨頭 更新時間: 2023-11-26 編程語言

XMLHttpRequest對象的Get請求和Post請求的用法

Get請求提交數據

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>發送ajax get請求</title>
</head>
<body>
<script type="text/javascript">
    window.onload = function (){
        var ajaxBtn= document.getElementById("ajaxBtn");
        ajaxBtn.onclick = function (){
            // 第一步:創建XMLHttpRequest對象
            var request = new XMLHttpRequest();
            // 第二步:注冊回調函數
            request.onreadystatechange = function () {
                    if (this.readyState == 4) {
                        if (this.status == 200) {
                            // innerHTML可以設置元素內部的HTML代碼。(innerHTML可以將后面的內容當做一段HTML代碼解釋并執行)
                            document.getElementById("mydiv").innerHTML = this.responseText
                        }else{
                            // status:返回請求的狀態號
                            alert(this.status)
                        }
                    }
            }
            // 第三步:開啟通道
            request.open("Get", "/ajax1/ajaxrequest1", true)
            // 第四步:發送請求
            request.send()
        }
    }
</script>

<input type="button" value="ajax" id="ajaxBtn">
<div id="mydiv"></div>
</body>
</html>
package com.ajax.servlet;

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

import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/ajaxrequest1")
public class AjaxRequest extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        out.print("<font>hello ajax</font>");
    }
}

Post請求提交數據

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script type="text/javascript">
    window.onload = function () {
        document.getElementById("btn").onclick = function () {
            // 第一步:創建XMLHttpRequest對象
            var xhr = new XMLHttpRequest();
            // 第二步:注冊回調函數
            xhr.onreadystatechange = function () {
                if(this.readyState == 4){
                    if (this.status == 200){
                        document.getElementById("mydiv").innerHTML = this.responseText
                    }else{
                        alert(this.status)
                    }
                }
            }
            // 第三步:開啟通道
            xhr.open("Post", "/ajax1/ajaxrequest", true)
            // 第四步:發送請求
            // 設置請求頭的內容類型,模擬Ajax提交form表單
            xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
            var username = document.getElementById("username").value;
            var password = document.getElementById("password").value;
            xhr.send("username="+username+"&password="+password )
        }
    }    
</script>

用戶名:<input type="text" id="username"><br>
密碼:<input type="text" id="password"><br>
<button id="btn">提交</button>

<div id="mydiv"></div>
</body>
</html>
package com.ajax.servlet;

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

import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/ajaxrequest")
public class AjaxRequest3Servlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        // 獲取提交的數據
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        out.print("用戶名:" + username);
        out.print("密碼:" + password);
    }
}

GET和POST請求時的區別

  • GET請求提交數據是在“請求行”上提交,而POST請求是在“請求頭”。
  • 所以,POST請求需要在open和send方法中添加一行代碼xxx.setRequestHeader(),用來設置請求頭的內容。

以上代碼中出現的XMLHttpRequest對象的方法和屬性

onreadystatechange屬性

  • 功能:定義當 readyState 屬性發生變化時被調用的函數
var xxx = new XMLHttpRequest();
xxx.onreadystatechange = function () {
        console.log(xxx.readyState)
    }
}

open()方法

  • 功能:開啟通道
  • open(method, url, async, user, psw)
    • method:請求的方式,可以是GET,也可以是POST,也可以是其它請求方式。
    • url:請求的路徑(/項目名/@WebServlet路徑)
      • 注:@WebServlet路徑可以隨便填寫,但是要和java代碼注解的@WebServlet(“/”)一致
    • async:只能是trve或者false,trve表示此ajax請求是一個異步請求,false表示此ajax請求是一個同步請求。
    • user(非必填項):用戶名 pwd:密碼,用戶名和密碼是進行身份認證的,說明要想訪問這個服務器上的資源,可能需要提供一些口令才能訪問。
xxx.open("Get", "/項目名/@WebServlet路徑", true)

send()方法

  • 功能:發送請求到服務器
// 發送GET請求到服務器
xxx.send()

// 發送POST請求到服務器
xxx.send(string)

responseText屬性

  • 功能:以字符串返回響應數據
// 在GET請求中出現的代碼
out.print("<font>hello ajax</font>");
document.getElementById("mydiv").innerHTML = this.responseText
    
<div id="mydiv"></div>
  • 以上代碼中的字符串內容通過responseText接收,并賦值給div標簽中,再使用innerHTML轉變成html代碼執行

status屬性

  • 功能:返回請求的狀態號(200: “OK”,404: “Not Found”…)

onblur失去焦點事件 和 onfocus獲取焦點

  • onblur功能:當失去焦點時,就發送Ajax POST請求,提交用戶名。
    • 什么叫失去焦點?
      • 當你將鼠標點在頁面搜索框中輸入時,會出現光標,而點擊到輸入框以外的地方,使得輸入框中的光標消失,則為失去焦點。
  • onfocus功能:獲取焦點
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>AJAX POST請求驗證同戶名是否可用</title>
</head>
<body>
<script type="text/javascript">
    window.onload = function () {
        document.getElementById("username").onfocus = function () {
            document.getElementById("tipMsg").innerHTML = ""
        }

        document.getElementById("username").onblur = function () {
            // console.log('失去焦點')
            var xhr = new XMLHttpRequest();
            xhr.onreadystatechange = function () {
                if (this.readyState == 4) {
                    if (this.status == 200) {
                        document.getElementById("tipMsg").innerHTML = this.responseText
                    }else {
                        alert(this.status)
                    }
                }
            }
            xhr.open("POST", "/ajax1/ajaxrequest5", true)
            xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
            var username = document.getElementById("username").value;
            xhr.send("username=" + username)
        }
    }
</script>
用戶名:<input type="text" id="username">

<span id="tipMsg"></span>
</body>
</html>

原文鏈接:https://blog.csdn.net/weixin_47957908/article/details/133900380

  • 上一篇:沒有了
  • 下一篇:沒有了
欄目分類
最近更新