How does php get the json string sent by ajax?
Front end:
$.ajax({
url: url ,
method: "post" ,
contentType: "application/json" ,
data: JSON.stringify({
name: "test"
})
});
server:
print_r($_REQUEST); // []
print_r($_POST); // []
print_r($_GET); // []
// !
print_r(file_get_contents("php://input")); // {"name": "test"}
do you want to send a json
string that can only be obtained through php://input
? What are the advantages of front-end and back-end data interaction in this way?
The underlying code of
1.php does a basic handling of the http request, and then puts in $_ GET,$_POST,$_REQUEST
2. When the request is a native json string, the underlying php cannot process it, so you can only get
3 from php://input
. For strongly typed languages, the advantage of using json is that they can convert json into objects, but it is not good for php
var json_data = JSON.stringify({
name: 'test'
});
$.ajax({
url: url ,
method: 'post' ,
data: {
p_data:json_data
}
});
$_ POST ['paired data'];
look it up on the Internet, the value format shown by the landlord is raw, which is often used to transmit multi-layer nested data, such as
.
{
"data": {
"data":{
"data":"value"
}
}
}
for the data in the figure above, it is not convenient to use raw when passing parameters in the form of key-value pairs.
for data reception methods, please refer to this URL:
Postman send raw data reception
of course, you can also turn the data into a json string and pass it in the form of key-value pairs. The backend needs to convert json to operate
.
contentType: 'application/x-www-form-urlencoded'
emmmm, gets data from php://input
, then transcodes and parses:
reference code: https://github.com/DXkite/sud.
generally, passing parameters with json type is suitable for more complex interactions. Through json, the backend can be directly mapped to an entity, which is convenient for backend code writing. At the same time, js is also friendly to json format, and many front-end developers are more convenient to deal with through json.