以JSON格式POST数据 [英] POST data in JSON format
本文介绍了以JSON格式POST数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一些数据需要转换为JSON格式,然后使用JavaScript函数进行POST。
I have some data that I need to convert to JSON format and then POST it with a JavaScript function.
<body onload="javascript:document.myform.submit()">
<form action="https://www.test.net/Services/RegistrationService.svc/InviteNewContact" method="post" name="myform">
<input name="firstName" value="harry" />
<input name="lastName" value="tester" />
<input name="toEmail" value="testtest@test.com" />
</form>
</body>
这就是帖子现在的样子。我需要它以JSON格式提交值并使用JavaScript进行POST。
This is the way the post looks now. I need it submit the values in JSON format and do the POST with JavaScript.
推荐答案
不确定是否需要jQuery。
Not sure if you want jQuery.
var form;
form.onsubmit = function (e) {
// stop the regular form submission
e.preventDefault();
// collect the form data while iterating over the inputs
var data = {};
for (var i = 0, ii = form.length; i < ii; ++i) {
var input = form[i];
if (input.name) {
data[input.name] = input.value;
}
}
// construct an HTTP request
var xhr = new XMLHttpRequest();
xhr.open(form.method, form.action, true);
xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
// send the collected data as JSON
xhr.send(JSON.stringify(data));
xhr.onloadend = function () {
// done
};
};
这篇关于以JSON格式POST数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文