json类型

  1. var api='http://127.0.0.1:7001/api/login';
  2. var data={
  3. a:1,
  4. b:2
  5. };
  6. var httpRequest = new XMLHttpRequest();//第一步:创建需要的对象
  7. httpRequest.open('POST', api, true); //第二步:打开连接
  8. httpRequest.setRequestHeader("Content-type","application/json");//设置请求头 注:post方式必须设置请求头(在建立连接后设置请求头)
  9. httpRequest.send(JSON.stringify(data));//发送请求
  10. /**
  11. * 获取数据后的处理程序
  12. */
  13. httpRequest.onreadystatechange = function () {//请求后的回调接口,可将请求成功后要执行的程序写在其中
  14. if (httpRequest.readyState == 4 && httpRequest.status == 200) {//验证请求是否发送成功
  15. var json = httpRequest.responseText;//获取到服务端返回的数据
  16. console.log(json);
  17. }
  18. };

form类型

  1. var httpRequest = new XMLHttpRequest();//第一步:创建需要的对象
  2. httpRequest.open('POST', 'http://127.0.0.1:7001/api/login', true); //第二步:打开连接
  3. httpRequest.setRequestHeader("Content-type","application/x-www-form-urlencoded");//设置请求头 注:post方式必须设置请求头(在建立连接后设置请求头)
  4. httpRequest.send("phone=13123123123&password=a11223344&type=phone");//发送请求
  5. /**
  6. * 获取数据后的处理程序
  7. */
  8. httpRequest.onreadystatechange = function () {//请求后的回调接口,可将请求成功后要执行的程序写在其中
  9. if (httpRequest.readyState == 4 && httpRequest.status == 200) {//验证请求是否发送成功
  10. var json = httpRequest.responseText;//获取到服务端返回的数据
  11. console.log(json);
  12. }
  13. };