Ajax POST JSON object gives php,php how to receive values
This post was last edited by ktosmaycry on 2014-07-04 20:30:03
Front:
$ ("#save_config_btn"). Click (function () {
$.ajaxsetup ({
Cache:false,
ContentType: "application/x-www-form-urlencoded; Charset=utf-8 "
});
var fields = $ ("#rss_form"). Serializearray ();
Fields = json.stringify (fields) //Chinese will be garbled
$.ajax ({
Type: "POST",
URL: "edit.php",
Data:fields,
Success:function (msg) {
Alert (msg);
}
});
});
Php:
Header ("content-type:text/html; Charset=utf-8 ");
$data = $_post[' data '];
Echo '';
Print_r ($data);
?>
The JSON format obtained through json.stringify is as follows:
[{"Name": "Bill", "Value": "Gates"},
{"Name": "George", "Value": "Bush"},
{"Name": "Thomas", "Value": "Carter"}]
PHP, where the Post's receive value does not know what to use, if the above JSON string is changed to the following format, then PHP can accept and directly return the array format
{"Data": [{"Name": "Bill", "Value": "Gates"},
{"Name": "George", "Value": "Bush"},
{"Name": "Thomas", "Value": "Carter"}]}
Two main questions to ask in summary:
1. How does jquery convert the JSON object obtained by Serializearray () to a JSON string in the second format and ensure that the Chinese is not garbled
2, or how PHP directly receives JSON objects or JSON strings in the first format
------Solution--------------------
1. How does jquery convert the JSON object obtained by Serializearray () to a JSON string in the second format and ensure that the Chinese is not garbled
Guaranteed not garbled, need to join in the header
The second format of the array
var fields = $ ("#rss_form"). Serializearray ();
var t = {};
t[' data ' = Fields
Fields = Json.stringify (t);
2, or how PHP directly receives JSON objects or JSON strings in the first format
Submit an example with the first JSON string:
demo.php
$data = $_post[' data '];
File_put_contents (' Test.log ', $data, true);
echo "OK";
?>
After running:
Test.log contents are [{"Name": "Chinese", "value": "Chinese"},{"name": "Chinese", "value": "Chinese"},{"name": "Chinese", "value": "Chinese"}]
If you do not add
It will be garbled.
------Solution--------------------
1, Ajax itself is UTF-8 encoded transmission, so there is no need to have CHARSET=UTF-8 statement
2, the JQ post method has been sent application/x-www-form-urlencoded head, do not need you to work again
So $.ajaxsetup ({
Cache:false,
ContentType: "application/x-www-form-urlencoded; Charset=utf-8 "
});
A paragraph is not needed. Consider the IE cache may affect the effect, you can use Cache:false as $.ajax parameters $.ajax ({
Cache:false,
Type: "POST",