PHP returns a JSON object to the front end

Source: Internet
Author: User
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!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.