带有变量查询的AJAX调用(POST)(纯JavaScript)

时间:2018-01-31 19:51:50

标签: javascript ajax forms

我正在尝试进行调用(POST),其XMLHttpRequest.open()中的网址及XMLHttpRequest.send()中的查询因条件而异。

所以我有一个选择表格:

<form id="myForm">
  <select name='options' id='options'>
    <option>One</option>
    <option>Two</option>
    <option>Three</option>
    <option>Another number</option>
  </select>
  <input type="submit">
</form>

如果选择“另一个号码”选项,则以编程方式添加新字段以创建新号码后的表单是:

<form>
  <select>
    <option></option>
    ...
  </select>
  <input type="text" name="ownOption" id="" ownOption> //New field in form created when 'Another number' is chosen.
  <input type="submit">
</form>

脚本是:

<script>
  var e = document.getElementById("options");
  var myQuery = ''
  var myUrl = 'firstUrl'
  e.addEventListener('change', function() {
      var index = e.selectedIndex;
      myQuery = e.options[index].text
      if (myQuery == 'Another number') {
        //Create new input field in form
        myUrl = 'secondUrl'
      } 
    })

    //Getting elements from new form after adding field programatically.
    var data = document.getElementById('myForm')

    //Listening to event and AJAX call
    data.addEventListener('submit', makeRequest);

    function makeRequest(e) {
      e.preventDefault();
      var xhr = new XMLHttpRequest()
      xhr.onreadystatechange = callback;
      xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
      xhr.open('POST', myUrl, true); //myUrl is 'firstUrl' or 'secondUrl' depending if 'Another number' is chosen or not-That works well
      //I want to do something like below; that is, alternative queries depending of a condition. The code below doesn't work
      if (myQuery == 'Another number') {
        xhr.send('clicks=' + data.elements[1].value) //From the new input field, second in order in the form.
      } else /*myQuery is any of the options but the last*/ {
        xhr.send('clicks=' + myQuery)
      }
    })
</script>

如何在XMLHttpRequest.send(query)中执行替代查询,具体取决于是否已通过新输入字段选择了某个给定选项或新选项。

1 个答案:

答案 0 :(得分:1)

首先,您需要一个帮助函数才能正确执行XMLHttpRequest,以便异步返回数据。例如:

var newXHR = null; // Once initialized with the XMLHttpRequest object, you can use the abort() method from anywhere in the code.

function sendXHR(options, callback) {
  newXHR = new XMLHttpRequest() || new window.ActiveXObject("Microsoft.XMLHTTP");
  newXHR.open(options.type, options.url, true);
  newXHR.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  newXHR.send(options.data);
  newXHR.onreadystatechange = function() {
    if (this.status === 200 && this.readyState === 4) {
      callback(this.response);
    }
  };
}

<强>用法:

sendXHR({
  url: myUrl,
  type: "POST",
  data: (myQuery === "Another number") ? "clicks=" + myForm.elements[1].value : "clicks=" + myQuery
}, function(response) {
  //console.log(response);
});

这样的事情:

&#13;
&#13;
(function() {
  var newXHR = null; // Once initialized with the XMLHttpRequest object, you can use the abort() method from anywhere in the code.

  function sendXHR(options, callback) {
    newXHR = new XMLHttpRequest() || new window.ActiveXObject("Microsoft.XMLHTTP");
    newXHR.open(options.type, options.url, true);
    newXHR.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    newXHR.send(options.data);
    newXHR.onreadystatechange = function() {
      if (this.status === 200 && this.readyState === 4) {
        callback(this.response);
      }
    };
  }

  var myForm = document.getElementById("myForm"),
    options = document.getElementById("options"),
    myQuery = "",
    myUrl = "https://httpbin.org/post?page=firstUrl";

  options.onchange = function() {
    myQuery = this.options[this.selectedIndex].text;
    if (myQuery === "Another number") {
      myUrl = "https://httpbin.org/post?page=secondUrl";
    }
  };

  myForm.onsubmit = function(e) {
    e.preventDefault();

    sendXHR({
      url: myUrl,
      type: "POST",
      data: (myQuery === "Another number") ? "clicks=" + myForm.elements[1].value : "clicks=" + myQuery
    }, function(response) {
      //console.log(response);
    });
  }
}());
&#13;
<form id="myForm">
  <select name='options' id='options'>
    <option>One</option>
    <option>Two</option>
    <option>Three</option>
    <option>Another number</option>
  </select>
  <input type="submit">
</form>
&#13;
&#13;
&#13;

希望这有帮助。