简体   繁体   English

无法从 Flask 到 Javascript AJAX ZC1C425268E68385D14AB5074C17A 返回多个变量

[英]Can't return multiple variables from Flask to Javascript AJAX function

I have a JS function that is updating subsequent select boxes based on the previous input.我有一个 JS function 正在根据先前的输入更新后续的 select 框。 I am populating these with responses from a Flask function that queries a database.我用来自查询数据库的 Flask function 的响应填充这些。 The issue is that the second variable that holds an array cannot be processed properly.问题是无法正确处理包含数组的第二个变量。 The first function works fine, but the second just has an undefinded variable.第一个 function 工作正常,但第二个只有一个未定义的变量。

JS Function JS Function

function update(deptcity, destsets, datesets, dtimesets) {

        $.ajax({
          
          url:"/returncity/?q="+deptcity, //the page containing python script
          type: "POST", //request type,
          dataType: 'json',
          data: JSON.stringify(deptcity)
        })

        .then( function updateDest(destsets, datesets) {
          
          console.log(datesets)
          var dest = destsets.destsets;
            
          var select = document.getElementById("destination");
          var length = select.options.length;

          for (i = length-1; i >= 0; i--) {
            select.options[i] = null;
          }

          var len = dest.length;
          for (i = len - 1; i >= 0; i--) {
            document.getElementById("destination").add(new Option(dest[i]));
          }

          

        })
          
        .then( function updateDate(datesets) {

          console.log(datesets);
          var date = datesets;

          var select = document.getElementById("date");
          var length = select.options.length;

          for (i = length - 1; i >= 0; i--) {
            select.options[i] = null;
          }

          var len = date.length;
          for (i = len - 1; i >= 0; i--) {
            document.getElementById("date").add(new Option(date[i]));
          }
        })
          
        ;

      }

Flask Function Flask Function

@views.route('/returncity/', methods = ['POST', 'GET'])
@login_required
def ajax_returncity():
    if request.method == 'POST':

        q = [request.get_json('data')]
        

        query = '''SELECT DISTINCT destination FROM Journey WHERE depart = ? ORDER BY destination ASC'''
        con = sqlite3.connect('Coach\database.db')
        cur = con.cursor()
        cur.execute(query, q)
        destrows = cur.fetchall()

        query = '''SELECT DISTINCT date FROM Journey WHERE depart = ? ORDER BY date ASC'''
        con = sqlite3.connect('Coach\database.db')
        cur = con.cursor()
        cur.execute(query, q)
        daterows = cur.fetchall()

        query = '''SELECT DISTINCT dtime FROM Journey WHERE depart = ? ORDER BY dtime ASC'''
        con = sqlite3.connect('Coach\database.db')
        cur = con.cursor()
        cur.execute(query, q)
        dtimerows = cur.fetchall()

        cur.close()
        con.close()

        destrow = []
        for i in destrows:
            for x in i:
                destrow.append(str(x))

        daterow = []
        for i in daterows:
            for x in i:
                daterow.append(str(x))
        print(daterow)
        
        dtimerow = []
        for i in dtimerows:
            for x in i:
                dtimerow.append(str(x))

        return jsonify(destsets = destrow, datesets = daterow, dtimesets = dtimerow)

I tried passing the variable through the first function to see if it would be accepted but it didn't.我尝试通过第一个 function 传递变量,看看它是否会被接受,但它没有。 The first function has it set to a string 'success'.第一个 function 将其设置为字符串“成功”。 The second function returns 'undefined'.第二个 function 返回“未定义”。

Thanks in advance for any help.提前感谢您的帮助。

The answer is to create a JSON object within the flask function and return it as one varibale as well as only using one JS function. The answer is to create a JSON object within the flask function and return it as one varibale as well as only using one JS function. I am not sure of the reasoning behind it as I guess I don't understand JSON and AJAX etc. very well.我不确定它背后的原因,因为我想我不太了解 JSON 和 AJAX 等。 Flask Flask

all_data = {'dest':destrow,'date':daterow, 'dtime':dtimerow}

return jsonify(all_data)

js js

function update(deptcity, data) {

    $.ajax({
      
      url:"/returncity/?q="+deptcity, //the page containing python script
      type: "POST", //request type,
      dataType: 'json',
      data: JSON.stringify(deptcity)
    })

    .then( function updateDest(data) {
      
      
      var dest = data.dest;
      console.log(dest);
        
      var select = document.getElementById("destination");
      var length = select.options.length;

      for (i = length-1; i >= 0; i--) {
        select.options[i] = null;
      }

      var len = dest.length;
      for (i = len - 1; i >= 0; i--) {
        document.getElementById("destination").add(new Option(dest[i]));
      }

      console.log(data.date);
      var date = data.date;

      var select = document.getElementById("date");
      var length = select.options.length;

      for (i = length - 1; i >= 0; i--) {
        select.options[i] = null;
      }

      var len = date.length;
      for (i = len - 1; i >= 0; i--) {
        document.getElementById("date").add(new Option(date[i]));
      }

      console.log(data.dtime);
      var dtime = data.dtime;

      var select = document.getElementById("dtime");
      var length = select.options.length;

      for (i = length - 1; i >= 0; i--) {
        select.options[i] = null;
      }

      var len = dtime.length;
      for (i = len - 1; i >= 0; i--) {
        document.getElementById("dtime").add(new Option(dtime[i]));
      }

    })
      
      
    ;

  }

You should only need one connection, and one cursor:您应该只需要一个连接和一个 cursor:

@views.route('/returncity/', methods = ['POST', 'GET'])
@login_required
def ajax_returncity():
    if request.method == 'POST':
        q = [request.get_json('data')]
        connection = sqlite3.connect('Coach/database.db')
        cursor = connection.cursor()
        
        query = '''SELECT DISTINCT destination FROM Journey WHERE depart = ? ORDER BY destination ASC'''
        cursor.execute(query, q)
        destrows = [dest for dest, in cursor]

        query = '''SELECT DISTINCT date FROM Journey WHERE depart = ? ORDER BY date ASC'''
        cursor.execute(query, q)
        daterows = [date for date, in cursor]

        query = '''SELECT DISTINCT dtime FROM Journey WHERE depart = ? ORDER BY dtime ASC'''
        cursor.execute(query, q)
        dtimerows = [dtime for dtime, in cursor]

        cursor.close()
        connection.close()

        return jsonify(destsets=destrows, datesets=daterows, dtimesets=dtimerows)

And you can only have one function, which get all the data:而且你只能有一个function,它可以得到所有的数据:

function update(deptcity, destsets, datesets, dtimesets) {
    $.ajax({
      url:"/returncity/?q="+deptcity, //the page containing python script
      type: "POST", //request type
      dataType: 'json',
      data: JSON.stringify(deptcity)
    })
    .then( function updateDest(data) {
      console.log(data)
      var select;
      select = document.getElementById("destination");
      for (i = select.options.length - 1; i >= 0; i--) {
        select.options[i] = null;
      }
      var dest = data.destsets;
      for (i = dest.length - 1; i >= 0; i--) {
        select.add(new Option(dest[i]));
      }

      select = document.getElementById("date");
      for (i = select.options.length - 1; i >= 0; i--) {
        select.options[i] = null;
      }

      var date = data.datesets;
      for (i = date.length - 1; i >= 0; i--) {
        select.add(new Option(date[i]));
      }
    });
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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