以JSON格式POST数据

编程入门 行业动态 更新时间:2024-10-23 04:41:56
本文介绍了以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="www.test/Services/RegistrationService.svc/InviteNewContact" method="post" name="myform"> <input name="firstName" value="harry" /> <input name="lastName" value="tester" /> <input name="toEmail" value="testtest@test" /> </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数据

本文发布于:2023-10-12 17:16:38,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1485357.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:格式   数据   JSON   POST

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!