【发布时间】:2019-11-21 17:33:23
【问题描述】:
我有一个 JS 前端,我在其中向 BE php 索引页面发出 Axios 请求。 BE页面有两个函数getAllData()和getSortedData()。
getSortedData 需要 2 个参数传入 sortBy 和 sortType。
如何调用相关函数并传入参数?
我试过这个:
axios({
method: 'post',
url: 'http://localhost/BE/index.php?f=getAllData',
timeout: 4000, // 4 seconds timeout
})
.then(response => {
return response.data;
})
.catch(error => console.error('timeout exceeded'));
但这不起作用,我需要将参数传递给第二个函数。
这是我的 PHP 索引页面,其中包含 2 个方法
<?php
header("Access-Control-Allow-Origin: *");
include_once 'GameListClass.php';
include_once 'DataClass.php';
include_once 'Classes/SortedDataClass.php';
function getSortedData($sortby, $asc) {
$json_games_list = getAllData();
$sorted_game_list = new SortedData();
return print_r(json_encode($sorted_game_list->getSortedJSONData($json_games_list, $sortby, $asc)));
}
function getAllData() {
$game_list = new GameList();
return peint_r(json_encode($game_list->getData()));
}
编辑
有没有比添加函数名和任何参数作为查询字符串更优雅的方法,即
?f=getAllData,
我可以作为参数传递吗?
例子:
axios({
method: 'post',
url: 'http://localhost/BE/index.php,
params: {
func: 'getAllData',
sortBy: 'name'
},
timeout: 4000, // 4 seconds timeout
})
.then(response => {
return response.data;
})
.catch(error => console.error('timeout exceeded'));
【问题讨论】:
-
改为将其作为 GET 请求发送,并在 PHP 端使用
$_GET['f']根据传入的参数决定使用哪个逻辑。 -
这对我不起作用,
-
会发生什么?它会抛出错误还是只是没有按预期运行?
-
错了它确实有效|我试图返回它来检查它的值而不是 print_r 谢谢
-
但是有没有更好的方法从 FE 传递函数调用和参数,感觉有点 Jacky?
标签: javascript php parameters axios