无效的Json用法?

编程入门 行业动态 更新时间:2024-10-28 06:27:44
本文介绍了无效的Json用法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

有时我 看到 的人将json发送给服务器的方式是:

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:

jsfiddle/sV5m4/1/-带有json标头的实际json

jsfiddle/sV5m4/1/ - Actual json with json header

在这里:

jsfiddle/sV5m4/2/-x-www-form -urlencoded标有标为json的标头

jsfiddle/sV5m4/2/ - x-www-form-urlencoded with header that claims to be json

更多推荐

无效的Json用法?

本文发布于:2023-11-09 09:07:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1571984.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Json

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!