总结ajax请求数据格式与响应数据格式
1.请求数据格式
浏览器是根据你设置的 请求头Content-Type 来解析你设置请求体的值的,所以请求头Content-Type的值要根据请求体格式的改变而改变!
//urlencoded格式请求体,对应的请求头Content-Type的值为application/x-www-form-urlencoded例子:
var xhr = new XMLHttpRequest();
xhr.open('POST', './05add.php');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send('age=11&sex=男');
//json格式请求体,对应的请求头Content-Type的值为application/json例子:
var xhr1 = new XMLHttpRequest();
xhr1.open('POST', '05add.php');
xhr1.setRequestHeader('Content-Type', 'application/json');
xhr1.send('{"sex":"男","age":11}');
2.响应数据格式
- 响应的数据格式一般是在后端的文件设置的
- 响应的数据格式是json格式,就要在后端开头设置—>header(‘Content-Type: application/json’);
<?php
header('Content-Type: application/json');
$data = array(
array(
'id' => 1,
'name' => '张三',
'age' => 18
),
array(
'id' => 2,
'name' => '李四',
'age' => 20
),
array(
'id' => 3,
'name' => '二傻子',
'age' => 18
),
array(
'id' => 4,
'name' => '三愣子',
'age' => 19
)
);
if (empty($_GET['id'])) {
$json = json_encode($data); // => [{"id":1,"name":"张三"},{...}]
echo $json;
} else {
foreach ($data as $item) {
if ($item['id'] != $_GET['id']) continue;
$json = json_encode($item); // => [{"id":1,"name":"张三"}]
echo $json;
}
}
- 响应的数据格式是xml格式的,就要在后端开头设置—>header(‘Content-Type: application/xml’);
<?php
header('Content-Type: application/xml');
?>
<?xml version="1.1" encoding="utf-8"?>
<person>
<name>石羊</name>
<age>16</age>
<gender>男</gender>
</person>
- 响应的数据格式是javascript格式的,就要在后端开头设置—>header(‘Content-Type: application/javascript’);
<?php
header('Content-Type: application/javascript');
// 写死的传送js脚本-----不推荐
//这样数据就传过去了,传过去的是js脚本,还需要在客户端执行一次回调才能拿到
// echo 'foo({"time":153142321})';
//以变量方式传入到需要传送js脚本------推荐,比较灵活
$json = json_encode(array(
'time' => time()
));
// 在 JSON 格式的字符串外面包裹了一个函数的调用,
// 返回的结果就变成了一段 JS 代码
echo "foo({$json})";
3.ajax请求xml格式数据
this.responseXML 专门用于获取服务端返回的 XML 数据,操作方式就是通过 DOM 的方式操作,但是需要服务端响应头中的 Content-Type 必须是 application/xml
var xhr = new XMLHttpRequest();
xhr.open('GET', '12xml.php');
xhr.send();
xhr.onreadystatechange = function () {
if (this.readyState !== 4) return;
// this.responseXML 专门用于获取服务端返回的 XML 数据,操作方式就是通过 DOM 的方式操作,但是需要服务端响应头中的 Content-Type 必须是 application/xml
// 下面的两种方法都可以获得内容
console.log(this.responseXML.documentElement.children[0].innerHTML);
console.log(this.responseXML.documentElement.getElementsByTagName('name')[0].innerHTML);
};
<?php
header('Content-Type: application/xml');
?>
<?xml version="1.1" encoding="utf-8"?>
<person>
<name>石羊</name>
<age>16</age>
<gender>男</gender>
</person>