首页 > 解决方案 > 无法使用 VueJs 从 Mysql DB 获取数据

问题描述

我尝试在前端使用vuejsaxios从mysql db 获取数据,但数据响应为. 此外,我检查了我的 php 代码,但没有发现问题,并且 php 代码本身可以正常工作。{{orderdtls.id}}null

PHP代码:

    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE');
    header('Access-Control-Allow-Headers: X-Requested-With,Origin,Content-Type,Cookie,Accept');
    $Catch_Query = json_decode(file_get_contents("php://input"));

 if($Catch_Query->action == 'fetchdata'){
    
              $orderid = $_GET['uniqid'];
              $getorder = "SELECT * FROM ordertbl WHERE uniqid='$orderid'";
              $order_query = $con->query($getorder);
              $order_init = $order_query->fetch_assoc();
              $Order_detalis = array();

              $Order_detalis[] = $order_init;
              echo json_encode($Order_detalis);
           
            }

Vue 脚本:

var OrderInfo = new Vue({
            el: '#rdp',
            data:{
                orderdtls:'',
            },
            methods:{
                fetchOrderDtls:function(){
                    axios.post(BaseUrl + '/core/core.php', {action:'fetchdata'}).then((response) => {
                        OrderInfo.orderdtls = response.data;
                        console.log(response);
                    }).catch(function(errors){
                        console.log(errors);
                    });
                }
            },
            created(){
                this.fetchOrderDtls();
            }


    });

这是控制台日志:

{data: "", status: 200, statusText: "", headers: {…}, config: {…}, …}
config: {url: "https://example.com/core/core.php", method: "post", data: "{"action":"fetchdata"}", headers: {…}, transformRequest: Array(1), …}
data: ""
headers: {access-control-allow-headers: "X-Requested-With,Origin,Content-Type,Cookie,Accept", access-control-allow-methods: "GET, POST, OPTIONS, PUT, DELETE", access-control-allow-origin: "*", content-length: "0", content-type: "text/html; charset=UTF-8", …}
request: XMLHttpRequest {readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, onreadystatechange: ƒ, …}
status: 200
statusText: ""
__proto__: Object

标签: javascriptphpmysqlvue.jsaxios

解决方案


编辑:聊天讨论显示 301 重定向导致有效负载无法到达服务器路由。下面的答案仍然有效。


代码需要uniqid在数据库调用的数据对象中传递一个。此外,$_GET由于您正在执行 axiospost而不是get.

uniqid与其他数据一起传递:

axios.post(BaseUrl + '/core/core.php', {
  action:'fetchdata',
  uniqid: 1                      // <-- Passing the `id` now as well ✅
}).then((response) => {
  OrderInfo.orderdtls = response.data;
  console.log(response);
}).catch(function(errors){
  console.log(errors);
});

在 PHP 后端,uniqid从存储的 post 数据中获取file_get_contents

if($Catch_Query->action == 'fetchdata'){
   $orderid = $Catch_Query->uniqid;
   ...
}

推荐阅读