使用json将用户名和密码发送到Web服务

时间:2012-12-21 06:43:32

标签: javascript json html5

您好我想在html 5中创建一个登录页面,但是为了登录我需要将用户名和密码发送到Web服务,Web服务已经创建,如果flase和它将返回值0任何其他数字如果是真的。我只能使用javascript和json。任何人都可以帮我理解json,因为我几乎一无所知。我如何使用json和javascript发送用户名和密码?

1 个答案:

答案 0 :(得分:2)

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