前端:
$("#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) //中文会乱码 $.ajax({ type: "POST", url : "edit.php", data: fields, success: function(msg){ alert(msg); } }); });
<?phpheader("Content-type: text/html; charset=UTF-8");$data = $_POST['data'];echo '<pre class="brush:php;toolbar:false">';print_r($data);?>
[{ "name":"Bill" , "value":"Gates" },{ "name":"George" , "value":"Bush" },{ "name":"Thomas" , "value":"Carter" }]
{"data":[{ "name":"Bill" , "value":"Gates" },{ "name":"George" , "value":"Bush" },{ "name":"Thomas" , "value":"Carter" }]}
1、JQuery如何把serializeArray()获取到的json对象转换为 第二种格式的json字符串 且保证中文不会乱码
保证不乱码,需要在header加入
第二种数组格式
var fields = $("#rss_form").serializeArray();
var t = {};
t['data'] = fields
fields = JSON.stringify(t);
2、或者php如何直接接收 json对象 或者 第一种格式的 json字符串
用第一种json字符串提交例子:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html> <head> <meta http-equiv="content-type" content="text/html;charset=utf-8"> <script src="//code.jquery.com/jquery-1.11.0.min.js"></script> <title> js test </title> </head> <body> <script type="text/javascript"> var fields = [{ "name":"中文" , "value":"中文" },{ "name":"中文" , "value":"中文" },{ "name":"中文" , "value":"中文" }]; fields = "data=" + JSON.stringify(fields); $.ajax({ type: "POST", url : "demo.php", data: fields, success: function(msg){ alert(msg); } }); </script> </body></html>
<?php$data = $_POST['data'];file_put_contents('test.log', $data, true);echo "ok";?>
1、ajax 本身就是以 utf-8 编码传输,所以不需要再有 charset=utf-8 声明
2、jq 的 post 方式已经发了 application/x-www-form-urlencoded 头,也不需要你再劳动了
所以
$.ajaxSetup({ cache:false, contentType : "application/x-www-form-urlencoded; charset=utf-8" });
$.ajax({ cache: false, type: "POST",
<xmp><?phpecho $s = print_r($_POST, 1);var_dump('is utf-8 ?', mb_check_encoding($s, 'utf-8'));
<script src=scripts/jquery-1.11.0.min.js></script><script src=scripts/json2.js></script><script>$(function() { $("#save_config_btn").click(function(){ var fields = $("#rss_form").serializeArray(); fields = JSON.stringify(fields); $.ajax({ cache: false, type: "POST", url : "jq_server.php", data: {data : fields}, //注意这里的写法 success: function(msg){ alert(msg); } }); });});</script><form id='rss_form'><input type=text name='比尔' value='大门'></br><input type=text name='乔治' value='布什'></br><input type=text name='托马斯' value='卡特'></br><input type=button id=save_config_btn value='ok'></form>
太感谢了,非常感谢两位的解答