XMLHttpRequest.send的数据php接收代码
时间: 2024-04-30 10:17:20 浏览: 17
好的,关于XMLHttpRequest.send的数据php接收代码,可以参考下面的示例:
JS代码:
```
var xhr = new XMLHttpRequest();
xhr.open('POST', 'example.php', true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
console.log(xhr.responseText);
}
};
var data = {
name: 'John',
age: 28
};
xhr.send(JSON.stringify(data));
```
PHP代码:
```
$data = json_decode(file_get_contents('php://input'), true);
echo 'Name: ' . $data['name'] . ', Age: ' . $data['age'];
```
以上代码中,XMLHttpRequest.send发送了一个包含name和age两个属性的JSON对象给example.php文件,然后在PHP文件中通过解析php://input获取JSON数据,并使用json_decode转换成数组,最后输出数据到控制台。
相关问题
Uncaught SyntaxError: Unexpected token '<', "<?php //从"... is not valid JSON at JSON.parse (<anonymous>) at XMLHttp.onreadystatechange (11ajaxA.html:18:28) XMLHttp.onreadystatechange @ 11ajaxA.html:18 XMLHttpRequest.send (async) (anonymous) @ 11ajaxA.html:13
这个错误通常是由于返回的数据不是有效的 JSON 格式引起的。在你的代码中,可能是因为你期望从服务器接收到 JSON 数据,但实际上返回的可能是一个 HTML 页面。
请确保你的服务器端代码正确地返回 JSON 格式的数据。你可以使用开发者工具检查网络请求的响应,并确保它返回的是有效的 JSON 数据。
ajax.send({})
`ajax.send({})` 并不是 AJAX 的正确语法。正确的 AJAX 请求通常使用 `XMLHttpRequest` 对象来发送请求,`send` 方法接收一个参数,即要发送的请求数据。常见的语法如下:
```
var xmlhttp = new XMLHttpRequest(); // 创建一个 XMLHttpRequest 对象
xmlhttp.onreadystatechange = function() { // 监听状态变化事件
if (this.readyState == 4 && this.status == 200) { // 当 readyState 为 4,status 为 200 时表示响应已就绪
console.log(this.responseText); // 打印响应内容
}
};
xmlhttp.open("GET", "example.php?name=value", true); // 指定请求方法、URL 和是否为异步请求
xmlhttp.send(); // 发送请求
```
在这个例子中,我们使用 `GET` 请求方式来向 `example.php` 发送请求,并且带有一个名为 `name` 的参数,值为 `value`。在发送请求后,我们监听 `onreadystatechange` 事件,当事件触发时,判断 `readyState` 和 `status` 是否符合预期,如果符合说明响应已就绪,我们可以通过 `responseText` 属性获取响应内容。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)