Home > Backend Development > PHP Tutorial > PHP realizes front-end and back-end data value transfer through json

PHP realizes front-end and back-end data value transfer through json

小云云
Release: 2023-03-22 10:44:01
Original
2613 people have browsed it

This article mainly shares with you how PHP realizes front-end and back-end data value transfer through json. It is mainly shared with you in the form of code. I hope it can help you.

Front-end key code (need to download jquery-3.3.1):

<script src="js/jquery-3.3.1.min.js"  type="text/javascript"></script>
    <script>
    $(function(){
        $("#btn").click(function(){
                var my_data="前端变量";            
                $.ajax({
                    url: "translate.php",  
                    type: "POST",
                    data:{trans_data:my_data},
                    error: function(){  
                        alert(&#39;&#39;);  
                    },                   
                    complete:function()
                    {
                        //location.href = "index.php?trans_data=" + my_data;
                    },  
                    success: function(data){//如果调用php成功                                                
                        var dataObj=eval("("+data+")");
                        alert(dataObj.name);
                    } 
                });
        });            
    });     
    </script>
......
<form action="translate.php" method="post">
      <input type="text" name="title" value="标题"/>
      <input id="btn" type="button" value="点击"/>
</form>
Copy after login

Backend translate.php code:

<?php
    header(&#39;Content-Type: text/html; charset=UTF-8&#39;); 
    $backValue=$_POST[&#39;trans_data&#39;];
    $info = array(&#39;name&#39; =>&#39;张三&#39;,&#39;sex&#39;=>&#39;男&#39;);
    if(isset($backValue)){
        echo json_encode($info);
    }
Copy after login

Related recommendations:

Implementing the value transfer function of session and cookie data in PHP

The above is the detailed content of PHP realizes front-end and back-end data value transfer through json. 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