83 javascript post json xmlhttprequest
我有一些数据需要转换为JSON格式,然后用JavaScript函数POST它.
<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>
Run Code Online (Sandbox Code Playgroud)
这是帖子现在的样子.我需要它以JSON格式提交值并使用JavaScript进行POST.
J. *_* K. 156
不确定你是否想要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
};
};
Run Code Online (Sandbox Code Playgroud)
Jos*_*ola 29
这是一个使用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>
Run Code Online (Sandbox Code Playgroud)
jQuery serializeArray函数使用表单值创建一个Javascript对象.然后,如果需要,您可以使用JSON.stringify将其转换为字符串.而且你也可以移除你的身体负荷.
归档时间: |
|
查看次数: |
271368 次 |
最近记录: |