如何在XMLHttpRequest POST请求成功后获取数据并展示到HTML页面
嘿,恭喜你的POST请求已经正常运行了!关于请求成功后获取返回数据并展示到页面,以及扩展GET、DELETE这些方法,我来给你一步步拆解清楚。
一、先解决当前核心问题:POST请求成功后获取并展示返回数据
其实核心就是利用XMLHttpRequest的onload事件(这个事件会在请求成功完成后触发),然后通过xhr.responseText或者解析后的JSON数据来更新页面DOM。
假设你现在的POST提交函数大概是这样,我给你修改并添加返回数据处理的部分:
function submitForm() { const xhr = new XMLHttpRequest(); xhr.open('POST', 'your-php-page.php', true); // 如果是表单提交,设置正确的Content-Type(如果用FormData可以不用这行,浏览器会自动处理) xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); // 重点:监听请求完成的事件 xhr.onload = function() { // 先判断请求状态码是否在成功范围内(200-299) if (xhr.status >= 200 && xhr.status < 300) { // 1. 获取返回数据:如果PHP返回的是纯文本/HTML,直接用xhr.responseText const rawResponse = xhr.responseText; // 2. 如果PHP返回的是JSON格式(推荐,更易处理结构化数据),要先解析 // const parsedResponse = JSON.parse(xhr.responseText); // 3. 把数据展示到页面:先找一个用来展示结果的DOM容器 const resultBox = document.getElementById('result-container'); // 纯文本展示 resultBox.textContent = `请求成功!返回内容:${rawResponse}`; // 如果是JSON数据,可以这样渲染(比如返回了用户信息) // resultBox.innerHTML = `<p>用户名:${parsedResponse.username}</p><p>提交时间:${parsedResponse.time}</p>`; } else { // 请求成功但状态码不对,处理错误 document.getElementById('result-container').textContent = `请求异常,状态码:${xhr.status}`; } }; // 别忘了监听网络错误(比如断网的情况) xhr.onerror = function() { document.getElementById('result-container').textContent = '网络出错啦,请检查连接'; }; // 收集表单数据并发送 const formData = new FormData(document.getElementById('your-form-id')); xhr.send(formData); }
对应的HTML里需要有一个展示结果的容器:
<!-- 放在页面合适的位置 --> <div id="result-container"></div>
PHP那边要确保返回正确的内容,比如返回JSON的话,要设置响应头:
<?php // 处理POST过来的表单数据 $name = $_POST['name']; $email = $_POST['email']; // 这里写你的业务逻辑,比如存入数据库 // 返回JSON格式的响应 header('Content-Type: application/json'); echo json_encode([ 'status' => 'success', 'message' => '数据提交成功', 'data' => [ 'name' => $name, 'email' => $email ] ]); ?>
二、扩展实现GET、DELETE请求方法
其实原理和POST基本一致,只是请求方法不同,参数传递的方式略有区别:
1. GET请求(用来获取数据)
GET请求的参数通常直接拼在URL后面:
function fetchUserData(userId) { const xhr = new XMLHttpRequest(); // 把参数拼在URL末尾 xhr.open('GET', `your-php-page.php?user_id=${userId}`, true); xhr.onload = function() { if (xhr.status >= 200 && xhr.status < 300) { const userData = JSON.parse(xhr.responseText); const resultBox = document.getElementById('result-container'); resultBox.innerHTML = ` <h3>用户信息</h3> <p>ID:${userData.id}</p> <p>姓名:${userData.name}</p> `; } else { document.getElementById('result-container').textContent = '获取数据失败'; } }; xhr.onerror = function() { document.getElementById('result-container').textContent = '网络错误'; }; // GET请求不需要send任何数据 xhr.send(); }
PHP处理GET请求:
<?php $userId = $_GET['user_id']; // 根据ID查询数据库获取用户数据 header('Content-Type: application/json'); echo json_encode([ 'id' => $userId, 'name' => '张三', 'email' => 'zhangsan@example.com' ]); ?>
2. DELETE请求(用来删除数据)
DELETE请求的参数可以拼在URL,也可以放在请求体里,这里用URL参数的示例:
function deleteUserData(userId) { const xhr = new XMLHttpRequest(); xhr.open('DELETE', `your-php-page.php?user_id=${userId}`, true); xhr.onload = function() { if (xhr.status >= 200 && xhr.status < 300) { const response = JSON.parse(xhr.responseText); document.getElementById('result-container').textContent = response.message; } else { document.getElementById('result-container').textContent = `删除失败,状态码:${xhr.status}`; } }; xhr.onerror = function() { document.getElementById('result-container').textContent = '网络错误'; }; xhr.send(); }
PHP处理DELETE请求:
<?php $userId = $_GET['user_id']; // 执行删除逻辑 header('Content-Type: application/json'); echo json_encode([ 'status' => 'success', 'message' => `ID为${userId}的用户已删除` ]); ?>
几个关键注意点
- 一定要监听
onload而不是onreadystatechange(虽然后者也能用,但onload更简洁,专门处理请求完成的情况) - 记得判断状态码,200-299才是成功的请求
- 如果返回JSON,PHP必须设置
Content-Type: application/json的响应头,否则前端解析可能出问题 - 操作DOM时,根据需要选择
textContent(纯文本,更安全)或innerHTML(可以渲染HTML标签)
内容的提问来源于stack exchange,提问作者Nevil Saul Blemuss
相关产品推荐
相关产品推荐

