【问题标题】:PHP does not execute function called via Axios in Vue.JSPHP 不执行在 Vue.JS 中通过 Axios 调用的函数
【发布时间】:2020-04-05 12:10:35
【问题描述】:

我正在尝试编写一个 Vue.JS 模块来进行一些数据处理并将变量发送到单独文件中的 PHP 函数。我正在使用 Axios 将参数解析为 PHP。现在的问题是,Axios 请求到达了 PHP 文件,但 PHP 并没有真正调用本来打算调用的函数。

来自 Vue 应用的 PHP 调用:

axios.post('./crmFunctions.php',{ params: { function2call:"sendQuery", id:1, mid:1, message: "Hello there!", event:"Query" }})
.then(response => this.responseData = response.data)
.catch(error => {});

PHP解释代码:

if(isset($_POST['function2call']) && !empty($_POST['function2call'])) {
    if( !isset($_POST['arguments']) ) { $aResult['error'] = 'No function arguments!'; }{
    $function2call = $_POST['function2call'];

    switch($function2call) {

    case 'sendQuery' : sendQuery($_POST['arguments'][0],$_POST['arguments'][1],$_POST['arguments'][2],$_POST['arguments'][3]);
    break;
    case 'other' : // do something;break;
        // other cases
    }
}
}

这段代码哪里出错了?我之前设法在 AJAX 上调用了相同的函数。

【问题讨论】:

    标签: javascript php html vue.js axios


    【解决方案1】:

    用 axios 发送的数据没有放入 PHP 的$_POST。 相反,它位于请求正文中,并且很可能是 json 格式。 要获取它,请尝试以下代码:

    function getRequestDataBody()
    {
        $body = file_get_contents('php://input');
    
        if (empty($body)) {
            return [];
        }
    
        // Parse json body and notify when error occurs
        $data = json_decode($body, true);
        if (json_last_error()) {
            trigger_error(json_last_error_msg());
            return [];
        }
    
        return $data;
    }
    
    
    $data = getRequestDataBody();
    var_dump($data)
    

    【讨论】:

    • 我试过你的答案。但它仍然拒绝工作。我可以在网络的标头部分看到 PHP 作为请求负载接收的数据。
    • 对不起,我错了。我更新了对新解决方案的答案。可以试试吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-02
    • 2020-09-05
    • 2015-12-25
    • 2019-04-21
    • 2015-10-22
    • 2017-06-06
    • 1970-01-01
    相关资源
    最近更新 更多