JSON 格式的 POST 数据 [英] POST data in JSON format

查看:27
本文介绍了JSON 格式的 POST 数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些数据需要转换为 JSON 格式,然后使用 JavaScript 函数将其发布.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆