问题描述的不够清楚,你说的获取本地json文件是指:xhr.open('post' , url , true) 这边的 url 不是类似:php/test.php 这样的服务器脚本而是 test.json 这样的??
若是不通过php这样的服务器脚本来调度数据的话,直接请求文件内容也是可以的。
例如:
这里有三个 json 文件: test.json , test1.json ,test2.json
js:
var path = 'test.json'; // 只要更换:test1.json || test2.json 就可以切换成不同的内容
xhr.open('post' , path , true); //
xhr.setRequestHeader('Content-Type' , 'application/x-www-form-urlencoded');
xhr.send();
xhr.onreadystatechange = function(){
if (this.readyState === 4 && this.status === 200) {
console.log(this.responseText); // 可以查看到 test.json 中的数据
}
}
若是换成 php 的也是一样的效果:
js:
var sendData = 'require=test'; // 只要更换参数: require test1 || require = test2 就可切换不同内容
xhr.open('post' , 'test.php', true);
xhr.setRequestHeader('Content-Type' , 'application/x-www-form-urlencoded');
xhr.send(sendData);
xhr.onreadystatechange = function(){
if (this.readyState === 4 && this.status === 200) {
console.log(this.responseText); // 可以查看到 test.json 中的数据
}
}
test.php:
$require = $_POST['require'];
switch ($require)
{
case 'test':
require 'test.json';
exit;
case 'test1':
require 'test1.json';
exit;
.....
}
综上,个人觉得 php 增加了处理的功能,所以建议还是xhr发送相关参数到 php 进行处理后反馈回数据的好,而不是直接请求不经处理的原始文本数据