发送与Axios的参数 - VueJS

时间:2017-09-06 19:09:29

标签: php vue.js axios

所以我在VueJS中与Axios合作发送ajax请求。但是,在尝试发送请求时,我遇到了一些问题。

这是我的JS代码:

axios.post('http://localhost/app/php/search.php', {
    query: this.search //this should send the 'query' param
}).then(response => {
    this.variable = response.data
}).catch(e => {
    this.errors.push(e)
})

这是search.php文件:

<?php

    require '../Functions.php';
    $obj = new Functions();

    $array = $obj->search($_POST['query']);

    echo json_encode(array_values($array));
?>

我在PHP方面遇到以下错误:Notice: Undefined index: query in /path/to/app/search.php on line 6

为什么会发生这种情况的原因?非常感谢任何帮助。

更新

this.search是我data对象中的变量:

data () {
    return {
      search: ''
    }
  }

此变量绑定到文本字段:

<input type="text" v-model="search" @keyup.enter="search()" />

我的search()方法中的这个是我的axios请求。

1 个答案:

答案 0 :(得分:1)

好的,所以我在Angular中看到了类似的问题,结果发现Axios发送了query param。但是,在php文件中,我不得不使用来自Axios的JSON填充POST变量。这就是我的工作方式:

<?php

    require '../Functions.php';
    $obj = new Functions();

    //Populate POST variable with incoming JSON from Axios.
    if ($_SERVER['REQUEST_METHOD'] == 'POST' && empty($_POST)):
        $_POST = (array) json_decode(file_get_contents('php://input'), true);
    endif;

    $array = $obj->search($_POST['query']);

    echo json_encode(array_values($array));
?>