使用Json和javascript(无jQuery)发布请求

时间:2018-09-25 10:59:14

标签: javascript json post request

我想获取每个<input/>的值并将其作为JSON请求发送。

这是表格。

<form class="formidable">
      <p>Date, heure et lieu de naissance</p>
      <input type="text" name="day" id="day" placeholder="Jour">
      <input type="text" name="month" id="month" placeholder="Mois">
      <input type="text" name="year" placeholder="Année">
      <input type="text" name="hour" id="hour" placeholder="Heure">
      <input type="text" name="minutes" id="minutes" placeholder="minutes">
      <input type="text" name="birthCity" placeholder="Ville">
      <input type="text" name="birthCountryLabel" placeholder="Pays">
      <input type="text" name="birthCountryCode" placeholder="Code postal">
      <input type="submit" name="button" value="submit" id="signin-login" onclick="GameJs()">
  </form>

这是我已经尝试过的:(我先设置了所有变量)

function GameJs() {
    xhr = new XMLHttpRequest();

    xhr.open('POST', 'url');
    xhr.setRequestHeader('Accept', 'application/json');
    xhr.onload = function () {
        if (xhr.status === 200) {
            alert(xhr.responseText);
        }
        else if (xhr.status !== 200) {
            alert('Request failed.  Returned status of ' + xhr.status);
        }
    };
    xhr.send(encodeURI(day));
    alert(birthCity);
}

我从服务器收到响应,但无法发送<input/>值。

2 个答案:

答案 0 :(得分:0)

我了解您是该网站的新手,但我要求您在发布新问题之前先查看现有的问题和答案。

从您的问题和代码来看,您似乎希望将整个表单传递给发布请求。要获取表单数据,可以使用以下命令:

var data= new FormData(document.querySelector('form'))

这是html5功能。您可以将data传递到POST,并且应该在后端获取所有数据。

答案 1 :(得分:0)

您可以像这样编辑JS函数:

function GameJs(){
    var day = document.getElementById('day');
    var month = document.getElementById('month');
    var year = document.getElementsByName('year')[0];
    var hour = document.getElementById('hour');
    var minutes = document.getElementById('minutes');
    var birthCity = document.getElementsByName('birthCity')[0];
    var birthCountryLabel = document.getElementsByName('birthCountryLabel')[0];
    var birthCountryCode = document.getElementsByName('birthCountryCode')[0];

    var x = {};
      x[day.name.toString()]= day.value;
      x[month.name.toString()]= month.value;
      x[year.name.toString()]= year.value;
      x[hour.name.toString()]= hour.value;
      x[minutes.name.toString()]= minutes.value;
      x[birthCity.name.toString()]= birthCity.value;
      x[birthCountryLabel.name.toString()]= birthCountryLabel.value;
      x[birthCountryCode.name.toString()]= birthCountryCode.value;
    console.log(x);
    //your post code here, post the variable x as the data
    return false;
}

,然后在html上,将提交按钮编辑为

  <input type="submit" name="button" value="submit" id="signin-login" onclick="return GameJs()">

这是一个fiddle