This article mainly introduces about PHP to the front end to return a JSON object, has a certain reference value, now share to everyone, the need for friends can refer to
Problem solving: How to return a JSON-formatted "object" to the front-end Ajax request when using PHP for the background;
Description: I am a front end, after working long time found that if you do not master a back-end development language, always feel a little weak. Recently in the side to do their own personal site learning PHP, while writing verification code verification, need to give the front-end authentication request to return a convenient data, so naturally think of returning a JSON format "object".
In the online search a lot of writing, helpless most do not, finally found the reason and rewrite code in StackOverflow, pro-test useful, so record down, hope to yimeimei helpful.
The code is as follows:
<?php/* Verify that the verification code is correct */session_start (); $code = Trim ($_post[' code ');//Receive data from the front end $raw_success = Array (' Code ' = 1, ' msg ' = = ' Verification code correct '); $raw _fail = Array (' Code ' = ' 2, ' msg ' = ' authenticode error '); $res _success = Json_encode ($raw _success); $res _ Fail = Json_encode ($raw _fail); header (' Content-type:application/json ');//This type declaration is very critical if ($code = = $_session["Verfycode "]) {echo $res _success;} else {echo $res _fail;}? >
So the front-end received data is an object, the front-end operation is very convenient.
If the validation succeeds, it returns {code:1,msg: "The captcha is correct"}; The failure is {code:2,msg: "Captcha Error"};
Because I am not a professional PHP development, so the great God saw, there is a better way, please point out, thank you!