如何通过AJAX发送YAML?

时间:2021-07-12 06:34:54

Please focus on the technical aspect of this question, and not on the why. The why is obvious: YAML is the most human-readable data serialization format available to man. And therefore, the best.

请关注这个问题的技术方面,而不是原因。原因很明显:YAML是人类可用的最易读的数据序列化格式。因此,最好的。

How can I send YAML via an XMLHttpRequest from the client to the server, without first converting it to JSON, XML or another format?

如何通过XMLHttpRequest从客户端向服务器发送YAML,而无需先将其转换为JSON,XML或其他格式?

I am using JavaScript for the client-side code, I can use jQuery if needed. My server-side language of choice is PHP.

我使用JavaScript作为客户端代码,如果需要我可以使用jQuery。我选择的服务器端语言是PHP。

According to Wikipedia, the send() method of XMLHttpRequest:

根据Wikipedia,XMLHttpRequest的send()方法:

Accepts a single parameter containing the content to be sent with the request. The W3C draft states that this parameter may be any type available to the scripting language as long as it can be turned into a text string, with the exception of the DOM document object. [Emphasis my own]

接受包含要随请求一起发送的内容的单个参数。 W3C草案声明该参数可以是脚本语言可用的任何类型,只要它可以转换为文本字符串,DOM文档对象除外。 [强调我自己]

YAML is a text string. Can it be sent and subsequently parsed correctly on the server-side without using another data serialization format like json, xml etc?

YAML是一个文本字符串。是否可以在服务器端发送并随后正确解析而不使用其他数据序列化格式,如json,xml等?

1 个解决方案

#1


4  

Just set an appropriate content type and send it.

只需设置适当的内容类型并发送即可。

// xhr is an instance of XMLHttpRequest which has been open()ed and had event handlers set on it already
xhr.setRequestHeader("Content-Type", "text/x-yaml");
xhr.send(string_of_yaml_formatted_data);

Note, that most server side languages won't parse it automatically, so you'll need to read the raw data from the POST request body and parse it yourself.

请注意,大多数服务器端语言都不会自动解析它,因此您需要从POST请求正文中读取原始数据并自行解析。

e.g. in PHP:

例如在PHP中:

$raw_yaml = file_get_contents('php://input');
$data = yaml_parse($raw_yaml);

Note: yaml_parse() requires PECL yaml >= 0.4.0

注意:yaml_parse()要求PECL yaml> = 0.4.0

#1


4  

Just set an appropriate content type and send it.

只需设置适当的内容类型并发送即可。

// xhr is an instance of XMLHttpRequest which has been open()ed and had event handlers set on it already
xhr.setRequestHeader("Content-Type", "text/x-yaml");
xhr.send(string_of_yaml_formatted_data);

Note, that most server side languages won't parse it automatically, so you'll need to read the raw data from the POST request body and parse it yourself.

请注意,大多数服务器端语言都不会自动解析它,因此您需要从POST请求正文中读取原始数据并自行解析。

e.g. in PHP:

例如在PHP中:

$raw_yaml = file_get_contents('php://input');
$data = yaml_parse($raw_yaml);

Note: yaml_parse() requires PECL yaml >= 0.4.0

注意:yaml_parse()要求PECL yaml> = 0.4.0