Опубликовать запрос с использованием Json и javascript (без jQuery) - PullRequest
0 голосов
/ 25 сентября 2018

Я хочу взять значение каждого <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 голосов
/ 25 сентября 2018

Вы можете отредактировать свою функцию 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()">

, здесь есть скрипка

0 голосов
/ 25 сентября 2018

Я понимаю, что вы новичок на сайте, но я бы попросил вас изучить существующие вопросы и ответы, прежде чем отправлять новый вопрос.

Судя по вашему вопросу и коду, кажется, что вы хотите пройтиВся форма на запрос поста.Чтобы получить данные формы, вы можете использовать следующее:

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

Это функция html5.Вы можете передать data в POST, и вы должны получить все данные на своем сервере.

...