Table of Contents
1. Preface
2. Currently, the data form that $_POST can receive
3. Solution
1. The front-end converts the data into QueryString
2. Use PHP back-end php://input gets the original data
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

Jul 10, 2018 pm 03:34 PM
javascript php vue.js yii

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1246
24
PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

Vue.js vs. React: Project-Specific Considerations Vue.js vs. React: Project-Specific Considerations Apr 09, 2025 am 12:01 AM

Vue.js is suitable for small and medium-sized projects and fast iterations, while React is suitable for large and complex applications. 1) Vue.js is easy to use and is suitable for situations where the team is insufficient or the project scale is small. 2) React has a richer ecosystem and is suitable for projects with high performance and complex functional needs.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

See all articles