Home > Software engineering >  Passing an array of values to a python flask server using JS
Passing an array of values to a python flask server using JS

Time:11-08

I am trying to send an array of module names and an array of marks to a function running on a python flask server.

  function getClassification()
  {
    const modulesArray = [
      document.getElementById('module_1').value,
      document.getElementById('module_2').value,
      document.getElementById('module_3').value,
      document.getElementById('module_4').value,
      document.getElementById('module_5').value
    ]
    const marksArray = [
      document.getElementById('mark_1').value,
      document.getElementById('mark_2').value,
      document.getElementById('mark_3').value,
      document.getElementById('mark_4').value,
      document.getElementById('mark_5').value
    ]
    let xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
        var j = JSON.parse(this.response);
      }
    };
    xhttp.open("GET",classifyModulesURL "?modules=" modulesArray "&marks=" marksArray);
    xhttp.send();
    return;
  }

When the flask server recieves the information, it is being treated as a string.

modules = request.args.get('modules')
print(modules)
marks = request.args.get('marks')
print(marks)
print(type(marks))

Outputs


CSC3021,CSC4302,CSC3299,CSC5678,CSC7623
45,66,43,54,78
<class 'str'>

I could do string manipulation on the python end to convert the strings to lists, but I thought the sending of the javascript array would preserve the structure. Have I done something wrong?

Thanks

modules = request.args.get('modules')
print(modules)
marks = request.args.get('marks')
print(marks)
print(type(marks))

Outputs


CSC3021,CSC4302,CSC3299,CSC5678,CSC7623
45,66,43,54,78
<class 'str'>

CodePudding user response:

This is because you are sending data as a query argument ( www.example.com?arg1=val1&arg2=val2 )which can only be sent as a string since they are part of the url. To preserve a list you should create a json object to be sent in the body of the POST request. At the same time the request must be handled correctly on the server side, i.e. you will no longer have to access the http request arguments, but its json content.

Look how to handle json request with flask.

Look how to post json with XMLHttpRequest

  • Related