用PHP视角来看,JSON就是PHP里的关联数组,就是键值对.
echo json_encode(array( 'A', 'B' )); // ["A","B"]
echo json_encode(array( 0 => 'A', 1 => 'B' )); // ["A","B"]
echo json_encode(array( 0 => 'A', 2 => 'B' )); // {"0":"A","2":"B"}
前端jQuery AJAX传输JSON给后端PHP.
前端:
var arr = {Client:"jQuery",Server:"PHP"}; //键名没有用双引号包围
var str = JSON.stringify(arr); //对象转为字符串后键名被加上了双引号
console.log(str); //输出 {"Client":"jQuery","Server":"PHP"}
var img = {};
$("img").each(function(index, ele){
//console.log("键:"+index+" 值:"+$(ele).attr('src'));
img[index] = $(ele).attr('src');
});
console.log(img); //输出 { 0="//c1.mifile.cn/1.png", 1="//c1.mifile.cn/2.png"}
$.post(
"http://127.0.0.1/test.php", //url:发送请求地址
{name:"ele", pass:"123", json:arr}, //data:待发送的K:V参数
function(data){ //callback:发送成功时的回调函数
console.log(data);
}
);
后端:
header('Content-Type: text/plain; charset=utf-8');
header('Access-Control-Allow-Origin: http://www.mi.com');
var_export($_POST);
//json:arr时输出
array (
'name' => 'ele',
'pass' => '123',
'json' =>
array (
'Client' => 'jQuery',
'Server' => 'PHP',
),
)
//json:str时输出
array (
'name' => 'ele',
'pass' => '123',
'json' => '{"Client":"jQuery","Server":"PHP"}',
)
//json:img时输出
array (
'name' => 'ele',
'pass' => '123',
'json' =>
array (
0 => '//c1.mifile.cn/1.png',
1 => '//c1.mifile.cn/2.png',
),
)