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

WBOY
Libérer: 2023-03-02 14:04:01
original
1121 Les gens l'ont consulté

本地ajax请求能否像php服务器一样,根据参数返回对应的数据?
我现在知道网页通过ajax请求能得到php中的数据,而且可以通过同一个地址,传递不同的data参数获得不同的数据,但是如果是获取本地的json文件能否达到同样的效果呢?

回复内容:

本地ajax请求能否像php服务器一样,根据参数返回对应的数据?
我现在知道网页通过ajax请求能得到php中的数据,而且可以通过同一个地址,传递不同的data参数获得不同的数据,但是如果是获取本地的json文件能否达到同样的效果呢?

不行,本地只能根据URL的不同来区分资源。
返回不同的数据,这个是需要服务器进行处理的,本地没有环境无法实现。其实你可以试试用node搭个简单的环境

问题描述的不够清楚,你说的获取本地json文件是指:xhr.open('post' , url , true) 这边的 url 不是类似:php/test.php 这样的服务器脚本而是 test.json 这样的??

若是不通过php这样的服务器脚本来调度数据的话,直接请求文件内容也是可以的。

例如:
这里有三个 json 文件: test.json , test1.json ,test2.json

<code>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 中的数据
    }
}</code>
Copier après la connexion

若是换成 php 的也是一样的效果:

<code>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;
   .....
 }</code>
Copier après la connexion

综上,个人觉得 php 增加了处理的功能,所以建议还是xhr发送相关参数到 php 进行处理后反馈回数据的好,而不是直接请求不经处理的原始文本数据

Étiquettes associées:
source:php.cn
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!