[英]Passing parameter to a PHP script from javaScript
我正在使用 PHP 脚本从 API 获取数据,并从 javaScript 文件中调用该脚本,该文件是在浏览器加载 DOM 后加载的意思。 我正在处理的网站有多个页面,每个页面都有一些从 API 获取的数据。 For example - A
page have data fetched from https://api.twitter.com/1.1/trends/place.json?id=1
while other page B
have data fetched from API with id=2
.
我的 PHP 脚本是:-
<?php
require_once('TwitterAPIExchange.php');
$settings = array(
'oauth_access_token' => "",
'oauth_access_token_secret' => "",
'consumer_key' => "",
'consumer_secret' => ""
);
$url = 'https://api.twitter.com/1.1/trends/place.json';
$getfield = '?id=1';
$requestMethod = 'GET';
$twitter = new TwitterAPIExchange($settings);
echo $twitter->setGetfield($getfield)
->buildOauth($url, $requestMethod)
->performRequest();
?>
我用于获取数据的 javascript 代码:-
fetch('1.php').then(function(response){ return response.json();})
.then(function(data){ appendData(data);})
.catch(function(error){ console.log(error);});
获取数据后,调用我已经编写的appendData()
。
在我的网站上,我有大约 30 个页面使用不同的 ID 调用这个 API。 我不想在我的 web 服务器上有 30 个 PHP 脚本。 有没有一种方法可以在 javascript 使用fetch()
调用时将 id 传递给javascript
脚本。
最简单的方法是将参数添加到您从中获取的 URL 中:
fetch('getData.php?id=1').then(...)
在您的getData.php
脚本中检查$_GET[]
数组中的参数:
if (!isset($_GET['id']) {
// Do something by default
} else {
switch($_GET['id']) {
case '1':
// do stuff
break;
case '2':
// do different stuff
break;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.