search
HomeBackend DevelopmentPHP TutorialHow 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
javascriptphpvue.jsyii

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

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

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>
  </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>

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'
            ],
            // 其他配置
        ],
        //其他组件配置
    ]

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
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
PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

See all articles

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 Article

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools