JSON 格式的 POST 数据

我有一些数据需要转换成 JSON 格式,然后用 JavaScript 函数发布它。

<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。

316136 次浏览

Here is an example using jQuery...

 <head>
<title>Test</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript" src="http://www.json.org/json2.js"></script>
<script type="text/javascript">
$(function() {
var frm = $(document.myform);
var dat = JSON.stringify(frm.serializeArray());


alert("I am about to POST this:\n\n" + dat);


$.post(
frm.attr("action"),
dat,
function(data) {
alert("Response: " + data);
}
);
});
</script>
</head>

The jQuery serializeArray function creates a Javascript object with the form values. Then you can use JSON.stringify to convert that into a string, if needed. And you can remove your body onload, too.

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
};
};

Using the new FormData object (and other ES6 stuff), you can do this to turn your entire form into JSON:

let data = {};
let formdata = new FormData(theform);
for (let tuple of formdata.entries()) data[tuple[0]] = tuple[1];

and then just xhr.send(JSON.stringify(data)); like in Jan's original answer.