Home >Backend Development >PHP Tutorial >PHP returns a JSON object to the front end
This article mainly introduces about PHP returning a JSON object to the front end. It has certain reference value. Now I share it with you. Friends in need can refer to it
Solution to the problem: When using PHP as the backend, how to return an "object" in JSON format to the AJAX request initiated by the front end;
Explanation: I I am a front-end person myself. After working for a long time, I found that if I don’t master a back-end development language, I always feel a little powerless. Recently, I was learning PHP while working on my own personal website. When writing I checked a lot of writing methods on the Internet, but most of them didn't work. Finally, I found the reason on stackThe code is as follows:
<?php /*验证验证码是否正确*/ session_start(); $code = trim($_POST['code']);//接收前端传来的数据 $raw_success = array('code' => 1, 'msg' => '验证码正确'); $raw_fail = array('code' => 2, 'msg' => '验证码错误'); $res_success = json_encode($raw_success); $res_fail = json_encode($raw_fail); header('Content-Type:application/json');//这个类型声明非常关键 if ($code == $_SESSION["verfycode"]) { echo $res_success; } else { echo $res_fail; } ?>In this way, the data received by the front-end is an object, and the front-end operation is very convenient. If the verification is successful, the response will be
{code:1,msg:"Verification code is correct"};If the verification fails, {code:2,msg:"Verification code is incorrect" };
Because I am not a professional PHP developer, so someone has seen it and has a better way, please give me some advice, thank you! Related recommendations:JSON PHP, the method of deserializing Json string into an object/array
PHP uses Method to return requested data in json or xml format
The above is the detailed content of PHP returns a JSON object to the front end. For more information, please follow other related articles on the PHP Chinese website!