微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript-如何通过AJAX发送YAML?

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.

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

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

根据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]

YAML是文本字符串.是否可以在不使用其他数据序列化格式(例如json,xml等)的情况下在服务器端将其发送并随后正确解析?

解决方法:

只是set一个appropriate内容类型和send它.

// 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);

请注意,大多数服务器端语言不会自动解析它,因此您需要从POST请求主体读取原始数据并自己解析.

例如在PHP中:

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

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐