Home >Backend Development >PHP Tutorial >PHP returns a JSON object to the front end

PHP returns a JSON object to the front end

不言
不言Original
2018-05-31 15:45:203562browse

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

Verification Code for verification, I needed to return an easy-to-operate data to the verification request initiated by the front end, so I naturally thought of returning a JSON format. "object".

I checked a lot of writing methods on the Internet, but most of them didn't work. Finally, I found the reason on stack

overflow and rewrote the code. I personally tested it and it worked, so I recorded it, hoping to be helpful to others in the future. .

The code is as follows:

<?php
	/*验证验证码是否正确*/
	session_start();
	$code = trim($_POST[&#39;code&#39;]);//接收前端传来的数据
	$raw_success = array(&#39;code&#39; => 1, &#39;msg&#39; => &#39;验证码正确&#39;);
	$raw_fail = array(&#39;code&#39; => 2, &#39;msg&#39; => &#39;验证码错误&#39;);
	
	$res_success = json_encode($raw_success);
	$res_fail = json_encode($raw_fail);
	
	header(&#39;Content-Type:application/json&#39;);//这个类型声明非常关键
	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!

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