PHP returns an example explanation of JSON object to the front end
- 2021-10-13 06:52:41
- OfStack
Solve the problem: When using php as the background, how to return an "object" in JSON format to the AJAX request initiated by the front end;
I am a front-end, after working for a long time found that if you do not master a back-end development language, the total feeling a little weak. Recently, I learned php while doing my own personal website. When writing verification code for verification, I need to return an easy-to-operate data to the verification request initiated by the front end, so I naturally thought of returning an "object" in JSON format.
I checked a lot of writing on the Internet, but most of them didn't work. Finally, I found the reason and rewrote the code on stackoverflow. The pro-test was useful, so I recorded it, hoping to help later people.
The code is as follows:
<?php
/* Verify that the verification code is correct */
session_start();
$code = trim($_POST['code']);// Receive the data from the front end
$raw_success = array('code' => 1, 'msg' => ' Verification code is correct ');
$raw_fail = array('code' => 2, 'msg' => ' Verification code error ');
$res_success = json_encode($raw_success);
$res_fail = json_encode($raw_fail);
header('Content-Type:application/json');// This type declaration is critical
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 is very convenient to operate.
If the verification is successful, it returns {code: 1, msg: "Verification code is correct"}; Failure is {code: 2, msg: "Verification code error"};
Because I am not a professional php development, so there is a great god to see, there is a better way, please point 1, thank you!