【问题标题】:How to read a python dictionary from the Jquery?如何从 Jquery 中读取 python 字典?
【发布时间】:2018-03-22 16:22:23
【问题描述】:

我的 python 函数为 My Jquery GET 调用返回一个字典值。

{'Site4': {'machine': 'null', 'state': 'unprocessed'}, 'Site2': {'machine': 'null', 'state': 'unprocessed'}, 'Site3': {'machine': 'null', 'state': 'unprocessed'}, 'Site1': {'machine': 'null', 'state': 'unprocessed'}}

我想在 html 表中分别显示站点/机器/状态值。我从 My GET 调用中获取了整个字典。

我的 Jquery 函数是;如下

function loadDoc() {
    var request;
    if (window.XMLHttpRequest) { // Mozilla, Safari, ...
      request = new XMLHttpRequest();
    } else if (window.ActiveXObject) { // IE
      try {
        request = new ActiveXObject('Msxml2.XMLHTTP');
      } 
      catch (e) {
        try {
          request = new ActiveXObject('Microsoft.XMLHTTP');
        } 
        catch (e) {}
      }
    }
    request.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
             var myObject = JSON.parse(this.responseText);
             alert(myObject);
          document.getElementById("demo").innerHTML =
          this.responseText;
        }
      };
    request.open('GET', 'http://localhost:8080/cache/getSite?clientName=testclient', true);
    request.send();
}

在上面的 JSON.parse 没有解析字典。如何在 jquery 中读取 python 字典值并在包含 3 列站点/机器/状态的表中显示?

我的 html 是;

<!DOCTYPE html>
<html>
<head>
<style>
table, th, td {
    border: 1px solid black;
}
</style>
<meta charset="UTF-8">
<title>Client Site Info</title>
</head>
<body>
<p id="demo"><button type="button" onclick="loadDoc()">load sites</button></p>
<table style="width:100%">
<caption>Client Site Info</caption>
  <tr>
    <th>Sites</th>
    <th>Machines</th> 
    <th>ProcessingState</th>
  </tr>
</table>
</body>

【问题讨论】:

  • 将字典发送到带有一些变量的 html 文件,x = 你的字典。在 jquery var dic = {{x|safe}} 中将显示字典
  • @AnandThati 我想分别读取站点/机器/状态值。我从 My GET 调用中获取了整个字典。

标签: jquery python html dictionary


【解决方案1】:

你可以试试:

$.ajax({
    type: 'POST',
    url: '',
    dataType: 'json',
    success:function(response){
        $("#loading").hide();
        if(response['success']== true){
            var dict_data = eval('(' + response['responseText'] + ')');

            $("#loading").hide();
        }
        else{
            alert("Problem in adding project in select box.");
        }
    },
    error: function (xhr, desc, err) {
        console.log(xhr);
        console.log("Desc: " + desc + "\nErr:" + err);
        $("#loading").hide();
    }
});

【讨论】:

    【解决方案2】:
    var _map = {
      'Site4': {
        'machine': 'null',
        'state': 'unprocessed'
      },
      'Site2': {
        'machine': 'null',
        'state': 'unprocessed'
      },
      'Site3': {
        'machine': 'null',
        'state': 'unprocessed'
      },
      'Site1': {
        'machine': 'null',
        'state': 'unprocessed'
      }
    };
    
    $.each(_map, function(key, value) {
      $.each(value, function(x, y) {
        $('body').append(key + ' ' + x + ' ' + y + '<br />')
      });
    });
    

    输出:

    Site4 machine null
    Site4 state unprocessed
    Site2 machine null
    Site2 state unprocessed
    Site3 machine null
    Site3 state unprocessed
    Site1 machine null
    Site1 state unprocessed
    

    JSfiddle code

    【讨论】:

      【解决方案3】:

      您可以使用$.ajax jquery 函数来完成,指定您的响应将是 JSON 格式,因此您不需要解析它。

      查看您的 HTML 代码,我假设您想将结果添加到表中,因此您可以创建行并将其添加到 ajax 调用的 success 函数中的表中...

      $('p#demo button').click(function() {
      
          $.ajax({
              type: 'GET',
              url: 'http://localhost:8080/cache/getSite?clientName=testclient',
              dataType: 'json',
              success: function(data) {
                  var rows = [];
                  $.each(data,function(id,value) {
                      rows.push('<tr><td>'+id+'</td><td>'+value.machine+'</td><td>'+value.state+'</td></tr>');
                  });
                  $('table').append(rows.join(''));
              }
          });
      });
      

      注意:请记住删除按钮中的onclick 属性...

      <p id="demo"><button type="button"">load sites</button></p>
      

      希望对你有帮助

      【讨论】:

      • 我删除了按钮并使用了 window.onload ,这就是我想要的谢谢
      • 很高兴听到!祝你有美好的一天,愉快的编码!
      【解决方案4】:

      为了测试环境,我设置了一个烧瓶应用程序。为了使JSON.parse 在jQuery 中正常工作,我在python 文件中使用了json.dumps。以下是文件:

      app.py:

      import json
      from flask import Flask, render_template
      
      app = Flask(__name__)
      
      @app.route('/')
      @app.route('/data')
      def get_data():
          data = {'Site4': {'machine': 'null', 'state': 'unprocessed'}, 'Site2': {'machine': 'null', 'state': 'unprocessed'}, 'Site3': {'machine': 'null', 'state': 'unprocessed'}, 'Site1': {'machine': 'null', 'state': 'unprocessed'}}
          return json.dumps(data)
      
      @app.route('/table')
      def show_table():
          return render_template("table.html")
      
      
      if __name__ == '__main__':
          app.run(debug=True)
      

      templates 文件夹中,table.html 包含:

      <!DOCTYPE html>
      <html>
      <head>
          <style>
          table, th, td {
              border: 1px solid black;
          }
      </style>
      <meta charset="UTF-8">
      <title>Client Site Info</title></head>
      <body>
          <p id="demo"><button type="button" onclick="loadDoc()">load sites</button></p>
          <table style="width:100%" id="table_data">
              <caption>Client Site Info</caption>
              <tr>
                  <th>Sites</th>
                  <th>Machines</th> 
                  <th>ProcessingState</th>
              </tr>
          </table>
          <script
          src="https://code.jquery.com/jquery-3.2.1.min.js"
          integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
          crossorigin="anonymous">
      </script>
      <script type="text/javascript">
          function loadDoc() {
              var request;
                  if (window.XMLHttpRequest) { // Mozilla, Safari, ...
                      request = new XMLHttpRequest();
                  } else if (window.ActiveXObject) { // IE
                      try {
                          request = new ActiveXObject('Msxml2.XMLHTTP');
                      } 
                      catch (e) {
                          try {
                              request = new ActiveXObject('Microsoft.XMLHTTP');
                          } 
                          catch (e) {}
                      }
                  }
                  request.onreadystatechange = function() {
                      if (this.readyState == 4 && this.status == 200) {
                          var myObject = JSON.parse(this.responseText);
                          for(key in myObject){
                              new_row = "<tr>";
                              new_row += "<td>";
                              new_row += key;
                              new_row += "</td>";
                              new_row += "<td>";
                              new_row += key["machine"];
                              new_row += "</td>";
                              new_row += "<td>";
                              new_row += key["state"];
                              new_row += "</td>";
                              new_row += "</tr>";
                              $('#table_data tr:last').after(new_row);
                          }
                      }
                  };
                  request.open('GET', 'http://127.0.0.1:5000/data', true);
                  request.send();
              }
          </script>
      </body>
      </html>
      

      输出如下:

      【讨论】:

      • 你做了很多工作,尽可能尝试用代码逻辑地回答。仅通过查看代码可能会帮助您解决问题。
      • @bhansa,感谢您的建议。我最近在开发使用 Flask 的应用程序时遇到了类似的问题。所以,我认为这可能有助于未来的 OP 从我所附的详细代码中获取要点。
      • 谢谢你..它的工作原理。我删除了那个按钮并使用了 window.onload
      【解决方案5】:

      var data = '{"Site4": {"machine": "null", "state": "unprocessed"}, "Site2": {"machine": "null", "state": "unprocessed"}, "Site3": {"machine": "null", "state": "unprocessed"}, "Site1": {"machine": "null", "state": "unprocessed"}}';
      
      var obj = $.parseJSON(data);
        $.each(obj, function() {
            console.log(this['machine']);
            console.log(this['state']);
        });
      &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt;

      【讨论】:

      • 这里的问题是我的字典总是用单引号返回值,而不是用双引号
      • 你需要在jQuery中用双引号替换单引号,然后解码Json,因为jQuery不解析单引号的json数据。
      猜你喜欢
      • 2014-08-31
      • 2018-08-27
      • 2022-11-28
      • 2015-02-23
      • 2015-12-24
      • 1970-01-01
      • 2021-05-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多