In PHP development we will encounter a data type called json. This type is similar to an array but not an array. Today we will talk about PHP reception json type of data, without further ado, let’s take a look at how PHP handles json!
Using Chrome's background network, we analyzed several situations when posting json data to PHP through $.ajax() of JQuery:
Unable In PHP, obtain json data through $_POST and $_REQUEST, that is,
$json = $_POST['json']; // empty($json) 为1
(Note: PHP only recognizes the application/x-www.form-urlencoded standard data type by default, so for types such as Content such as text/xml or soap or application/octet-stream cannot be parsed. If you use the $_POST array to receive it, it will fail)
##Case 1:
The attribute contentType is not added to js: "application/json; charset=utf-8",
var submit_sync = function() { $.ajax({ type: "post", url: 'add-post-json.php', async: false, // 使用同步方式 // 1 需要使用JSON.stringify 否则格式为 a=2&b=3&now=14... // 2 需要强制类型转换,否则格式为 {"a":"2","b":"3"} data: JSON.stringify({ a: parseInt($('input[name="a"]').val()), b: parseInt($('input[name="b"]').val()), now: new Date().getTime() // 注意不要在此行增加逗号 }), dataType: "json", success: function(data) { $('#result').text(data.result); } // 注意不要在此行增加逗号 }); }
The data cannot be obtained after using $GLOBALS['HTTP_RAW_POST_DATA'], that is,
$json = $GLOBALS['HTTP_RAW_POST_DATA']; // empty($json) 为 1
Use file_get_contents("php://input"); can obtain data, that is,
$json = file_get_contents("php://input"); // empty($json) 为 0
Case 2:
##Add the attribute contentType to js: "application/json; charset=utf-8",var submit_sync = function() {
$.ajax({
type: "post",
url: 'add-post-json.php',
async: false, // 使用同步方式
// 1 需要使用JSON.stringify 否则格式为 a=2&b=3&now=14...
// 2 需要强制类型转换,否则格式为 {"a":"2","b":"3"}
data: JSON.stringify({
a: parseInt($('input[name="a"]').val()),
b: parseInt($('input[name="b"]').val()),
now: new Date().getTime() // 注意不要在此行增加逗号
}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
$('#result').text(data.result);
} // 注意不要在此行增加逗号
});
}
$json = $GLOBALS['HTTP_RAW_POST_DATA']; // empty($json) 为 0
The above is all the content of this article, I hope it can be helpful to everyone! Related recommendations: Detailed explanation of usage examples of php json related functions The above is the detailed content of Several situations of JSON value transfer and PHP reception. For more information, please follow other related articles on the PHP Chinese website!$json = file_get_contents("php://input"); // empty($json) 为 0