总结:
new XMLHttpRequest()xhr.responseType = 'json'xhr.open("GET / POST", url, true)xhr.onload = () => console.log(xhr.response)xhr.setRequestHeater('content-type','application/json')xhr.onerror = () => console.log('Error')xhr.send(null / jsonString)XHR 示范HTML:
<!DOCTYPE html><html lang="zh-CN"><head><meta charset="UTF-8" /><meta http-equiv="X-UA-Compatible" content="IE=edge" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>传统的XHR: GET</title></head><body><button onclick="getUser(this)">XHR请求-GET</button><script>function getUser(btn) {// 1. 创建对象const xhr = new XMLHttpRequest();// 2. 响应类型xhr.responseType = 'json';// 3. 配置参数// xhr.open(请求类型,请求URL,请求方式)xhr.open('GET', 'http://ajaxtest.cn/data.php?id=2');// 4. 成功回调xhr.onload = function () {// xhr.response: 响应数据console.log(xhr.response);// DOM: 将响应数据渲染到页面中};// 5. 失败回调xhr.onerror = function () {console.log('Error');};// 6. 发送请求xhr.send(null);}</script></body></html>
<!DOCTYPE html><html lang="zh-CN"><head><meta charset="UTF-8" /><meta http-equiv="X-UA-Compatible" content="IE=edge" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>传统的XHR: POST</title></head><body><form action="" onsubmit="return false"><input type="text" /><input type="text" /><input type="text" /><button onclick="getUser(this)">XHR-POST请求</button></form><!-- <button onclick="getUser(this)">XHR-POST请求</button> --><script>function getUser(btn) {// 1. 创建对象const xhr = new XMLHttpRequest();// 2. 响应类型xhr.responseType = 'json';// 3. 配置参数// xhr.open(请求类型,请求URL,请求方式)xhr.open('POST', 'http://ajaxtest.cn/data.php?id=2');// 4. 设置请求头(POST)xhr.setRequestHeater('content-type', 'application/json');// 4. 成功回调xhr.onload = function () {// xhr.response: 响应数据console.log(xhr.response);// DOM: 将响应数据渲染到页面中};// 5. 失败回调xhr.onerror = function () {console.log('Error');};// 6. 发送请求xhr.send(JSON.stringify({ name: 'admin', email: 'admin@php.cn' }));}</script></body></html>
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号