php ajax 参数,本地ajax请求能否像php服务器一样,根据参数返回对应的数据??...

问题描述的不够清楚,你说的获取本地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 进行处理后反馈回数据的好,而不是直接请求不经处理的原始文本数据

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值