简体   繁体   中英

Sending variable data to server using XMLHttpRequest Get method in JavaScript?

I want to send one variable data to server using Get method in XMLHttpRequest . When we use Get type then we cannot send it in the body like Post so how can I send that variable xyz to server..

function getSearch() {

  var xyz = "vincent";
  var url = 'https://script.google.com/a/google.com/exec';
  var xhr = new XMLHttpRequest();

  xhr.onreadystatechange = function() {
    if (xhr.readyState == 4 && xhr.status == 200) {
      var link = JSON.parse(xhr.responseText);

    }
  }
  xhr.open('GET', url, true);
  xhr.send();

}

One such approach is to encode the parameters into your URL, hence you'll need to modify your code as per below.

Add the following line, where some_variable_name is the parameter name you're planning to pass across.

var params = "some_variable_name=xyz";
url = url + '?' + params;

Modify your xhr.open to include the new parameter:

xhr.open("GET", url, true);

Your code would look something like this:

function getSearch() {

  var xyz = "vincent";
  var url = 'https://script.google.com/a/google.com/exec';
  var params = '?some_variable_name=' + encodeURIComponent(xyz);
  var xhr = new XMLHttpRequest();

  url = url + params;
  xhr.open("GET", url, true);

  xhr.onreadystatechange = function() {
    if (xhr.readyState == 4 && xhr.status == 200) {
      var link = JSON.parse(xhr.responseText);

    }
  }

  xhr.send();

}

First make sure what type of data you want to send, if data is sensitive like password,email etc do not send it with the get request use post instead, although if you want to send param/varible data from get send it with URL query parameter like below

var xyz = "vincent";
var url = 'https://script.google.com/a/google.com/exec'+'? {name_of_param}='+xyz;

and at server you will be able to get the variable data by, req.query.{name_of_param}

Good luck

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM