无效的Json用法? [英] Invalid Json usages?
问题描述
Sometimes I see people send json to server as :
$.ajax({
url: ...
contentType: "application/json; charset=utf-8",
dataType: "json",
data: { 'page': '100AAAAAf00' },
responseType: "json",
success: ...,
error: ...
});
但是{ 'page': '100AAAAAf00' }
不是 Json.
并说contentType是json ...
and were saying contentType is json ...
Json是文本表示形式.
Json is the text representation.
例如:"{ 'page': '100AAAAAf00' }"
我在这里想念什么吗? (jQuery是否在幕后进行某些翻译?)
Am I missing something here ? ( Does jQuery is doing some translations behind the scenes ?)
Wiki:
JSON或JavaScript对象表示法,是基于文本的(!!) 专为人类可读的数据交换而设计的开放标准.
JSON or JavaScript Object Notation, is a text-based (!!) open standard designed for human-readable data interchange.
推荐答案
$.ajax("/", {
contentType: "application/json; charset=utf-8",
dataType: "json",
data: {
'page': '100AAAAAf00'
},
type: 'POST',
responseType: "json"
});
错.这将发送带有请求正文的普通application/x-www-form-urlencoded
请求:
Is wrong. This will send a normal application/x-www-form-urlencoded
request with the request body:
page=100AAAAAf00
但是,由于标头是"application/json; charset=utf-8"
,因此实际上是位于服务器上.
But since the header is "application/json; charset=utf-8"
, it is actually lying to the server.
要使用jQuery将真实,纯净,真实的JSON发送到服务器,您将使用:
To send, real, pure, actual JSON to the server with jQuery, you would use:
$.ajax("/", {
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify({ //If data is string, jQuery will not try to process it
'page': '100AAAAAf00'
}),
type: 'POST',
responseType: "json"
});
现在请求正文将是:
{"page":"100AAAAAf00"}
并且完全不能与php的$_POST
一起使用,因为它是基于application/x-www-form-urlencoded
的,
所以也许这就是为什么人们更喜欢前者的原因.
And that cannot be used with php's $_POST
at all since it works on the basis of application/x-www-form-urlencoded
,
so maybe that's why people prefer the former..
一个人可以使用开发人员工具中的Chrome的网络"标签在这里验证我的主张:
One can use Chrome's network tab in developer tools to verify my claims here:
http://jsfiddle.net/sV5m4/1/-带有json标头的实际json
http://jsfiddle.net/sV5m4/1/ - Actual json with json header
在这里:
http://jsfiddle.net/sV5m4/2/-x-www-form -urlencoded标有标为json的标头
http://jsfiddle.net/sV5m4/2/ - x-www-form-urlencoded with header that claims to be json
这篇关于无效的Json用法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!