素材巴巴 > 程序开发 >

AJAX应该如何发送请求

程序开发 2023-09-05 07:58:27

XMLHttpRequest对象

在这里插入图片描述

  • XMLHttpRequest对象的方法

  • 方法描述abort()取消当前请求getAllResponseHeaders()返回头部信息getResponseHeader()返回特定的头部信息open(method, url, async, user, psw)规定请求method:请求类型 GET 或 POSTurl:文件位置async:true(异步)或 false(同步)user:可选的用户名称psw:可选的密码send()将请求发送到服务器,用于 GET 请求send(string)将请求发送到服务器,用于 POST 请求setRequestHeader()向要发送的报头添加标签/值对 属性描述onreadystatechange定义当 readyState 属性发生变化时被调用的函数readyState保存 XMLHttpRequest 的状态。0:请求未初始化 1:服务器连接已建立 2:请求已收到 3:正在处理请求 4:请求已完成且响应已就绪responseText以字符串返回响应数据responseXML以 XML 数据返回响应数据status返回请求的状态号200: "OK"403: "Forbidden"404: “Not Found”statusText返回状态文本(比如 “OK” 或 “Not Found”)

    AJAX GET请求

    @WebServlet("/ajaxRequest")
     public class AjaxRequestServlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {PrintWriter out = response.getWriter();//XMLHttpRequest对象获取输出信息out.print("welcome to study ajax");}
     }
     
    
     

    AJAX POST请求

    模拟form的post请求

    
     用户名:
    密码:

    JSON

    Connection conn = null;PreparedStatement ps = null;ResultSet rs = null;ArrayList arrayList = new ArrayList<>();response.setContentType("text/html;charset=UTF-8");PrintWriter out = response.getWriter();try {conn = DbUtil.getConnection();String sql = "select * from stu";ps = conn.prepareStatement(sql);rs = ps.executeQuery();while (rs.next()) {String name = rs.getString("name");int age = rs.getInt("age");String address = rs.getString("address");Student student = new Student(name, age, address);arrayList.add(student);}out.print(JSON.toJSONString(arrayList));
     //前提是创建好User对象
     

    XML

    基于XML的小例子

     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {response.setContentType("text/xml;charset=UTF-8");PrintWriter out = response.getWriter();StringBuilder str = new StringBuilder();str.append("");str.append("");str.append("zhangsan");str.append("18");str.append("
    北京
    ");str.append("
    ");str.append("");str.append("lisi");str.append("18");str.append("
    上海
    ");str.append("
    ");str.append("
    ");out.print(str);}
     window.onload = function (){document.getElementById("btn").onclick = function (){var xhr = new XMLHttpRequest();xhr.onreadystatechange = function (){if (this.readyState ===4){if (this.status ===200){var stuDOC = this.responseXML;//返回一个xml对象var students = stuDOC.getElementsByTagName("Student")var html = ""for (let i = 0; i < students.length; i++) {html += ""var stu = students[i]var childNodes = stu.childNodes;html +=""+(i+1)+""for (let j = 0; j < childNodes.length; j++) {var node = childNodes[j]if (node.nodeName === "name"){html += ""+node.textContent+""}if(node.nodeName ==="age"){html += ""+node.textContent+""}if(node.nodeName ==="address"){html += ""+node.textContent+""}}html += ""}console.log(html)document.getElementById("stubody").innerHTML = html}else {alert("error")}}}xhr.open("GET","/ajax/g",true)xhr.send()}
     

    AJAX乱码问题


    
     ---## AJAX乱码问题- - 对于tomcat9来说呢?- 响应中文的时候,会出现乱码,怎么解决?```javaresponse.setContentType("text/html;charset=UTF-8");```- 发送ajax post请求的时候,发送给服务器的数据,服务器接收之后乱码,怎么解决?```javarequest.setCharacterEncoding("UTF-8");```---## AJAX的异步与同步
     

    标签:

    素材巴巴 Copyright © 2013-2021 http://www.sucaibaba.com/. Some Rights Reserved. 备案号:备案中。