Home > Backend Development > PHP Tutorial > How to let vue's axios component and PHP backend exchange data

How to let vue's axios component and PHP backend exchange data

不言
Release: 2023-04-02 22:38:01
Original
2671 people have browsed it

This article mainly introduces how to exchange data between Vue's axios component and PHP backend. It has certain reference value. Now I share it with you. Friends in need can refer to it

1. Preface

axios is a component in the vue project that uses ajax technology to exchange data with the background. Under the recommendation of the author of vue, a considerable number of vue front-end developers began to use it. However, during the actual development process, it sometimes happens that the backend cannot receive the data posted by the frontend. Taking the background of PHP language development as an example, PHP's native predefined variable $_POST cannot be received (because parsing failed). The purpose of this article is to explore front-end and back-end data interaction and provide different solutions for your reference.

2. Currently, the data form that $_POST can receive

Form Data
This data form is actually a key-value pair, such as id:1, if there is If there are multiple sets of key-value pairs and they are nested, then the following is the case

role-name:ta
role-desc:xxxxxxxxx
id:2
cloud[cla]:001
cloud[cla_baijia]:001
cloud[cla_gongkai]:001
local[soft5]:001
local[soft6]:001
mgmt[mgmt-clouditems]:01
Copy after login

The data received by the PHP server actually looks like this

role-name=ta&role-desc=xxxxxxxxx&id=2&cloud%5Bcla%5D=001&cloud%5Bcla_baijia%5D=001&cloud%5Bcla_gongkai%5D=001&local%5Bsoft-5%5D=001&local%5Bsoft-6%5D=001&mgmt%5Bmgmt-clouditems%5D=01
Copy after login

Is it particularly similar to the parameters of the url?
The data of this key-value pair is called QueryString. When the browser's native form sends this data, the request header will be set to application/x-www-form-urlencoded .
QueryString can be successfully parsed by PHP's $_POST

The serialize() method and param() method of jQuery ajax under the classic front-end library jQuery is to convert data into The solution provided by QueryString is that the former converts form data and the latter converts JSON data.
Moreover, jQuery's ajax request will determine the incoming data form and implicitly call the param() method to convert the json data. Therefore, the user only needs to directly provide the json data to successfully submit the data to the background. It needs to be explicitly There are not many opportunities to call the param() method (manually). The request header sent by jq by default is also application/x-www-form-urlencoded. In most cases, the user does not need to set it manually.

Back to our axios, the request header sent by axios by default is application/json. To put it simply, it will pass json to the backend by default and not convert it into QueryString. .

3. Solution

1. The front-end converts the data into QueryString

Introduce the qs library and call the stringify method

<template>
  <p>
      <input type="button" name="login" value="数据提交" @click="post">
  </p>
</template>

<script>
import axios from "axios"
import qs from "qs"
var json={
              "role-name": "ta",
              "role-desc": "xxxxxxxxx",
              "id": 2,
              "cloud": {
                "cla": "001",
                "cla_baijia": "001",
                "cla_gongkai": "001"
              },
              "local": {
                "soft-5": "001",
                "soft-6": "001"
              },
              "mgmt": {
                "mgmt-clouditems": "01"
              }
    };

export default {
    methods:{
        post(){
            axios.post("http://localhost/web/index.php/admin/login/login",json,{
                //配置`transformRequest` ,在向服务器发送前,修改请求数据,axios会根据修改后的数据,自动设置请求头
                transformRequest:[function(data){
                    return qs.stringify(data);//把数据转化为QueryString
                }]
            }).then(res=>{
                console.log(res);
            })
        }
    }
}
</script>
Copy after login

2. Use PHP back-end php://input gets the original data

Without any changes to the front-end, because the predefined variable $_POST cannot be parsed, the php back-end can only use php://input to get the original data, and then Then convert it into the desired data form.
If the PHP backend uses native development, you can customize a function to process the data of each request.
If the PHP backend is developed using a specific framework, it depends on whether the framework itself supports processing php://input. A simple test method is to search for php://input in the full text of the source code of the framework. If it can be found, If it is supported, otherwise it is not supported and you need to extend the relevant processing code yourself.

Taking the PHP framework yii2.0 as an example, search the vendor directory in full text, and you can see that there is relevant processing code in line 494 of yiisoft->yii2->web->Request.php.
In actual use, you only need to configure the configuration file web.php

    'components' => [
        'request' => [
            'parsers' => [
                'application/json' => 'yii\web\JsonParser'
            ],
            // 其他配置
        ],
        //其他组件配置
    ]
Copy after login

The above are two solutions for front-end processing and back-end processing, you can choose according to the actual situation

The above is the entire article Content, I hope it will be helpful to everyone’s learning. For more related content, please pay attention to the PHP Chinese website!

Related recommendations:

How to set up a long connection for the yii database

The above is the detailed content of How to let vue's axios component and PHP backend exchange data. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template