2017-10-11 53 views
1

我的python函數爲My Jquery GET調用返回一個字典值。如何從JQuery中讀取python字典?

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

我想顯示在一個html表網站/機器/狀態值分開。我從我的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> 
+0

送字典中的HTML文件與一些varibale,X =你的字典。在jquery var dic = {{x | safe}}將顯示字典 – 2017-10-11 05:48:18

+0

@AnandThati我想單獨讀取站點/機器/狀態值。我從我的GET調用中獲得整個字典。 – Ratha

回答

0

您可以$.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> 

我希望它能幫助

+0

我刪除了按鈕,並使用window.onload,這是我想要的謝謝 – Ratha

+0

好聽!祝你有美好的一天,快樂的編碼! –

1

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']); 
 
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

+0

這裏的問題是我的字典總是返回單引號值,而不是雙引號 – Ratha

+0

您需要用jQuery中的雙引號替換單引號,然後解碼Json,因爲jQuery不會用單引號解析json數據。 – javidrathod

+0

請參考此鏈接:http://www.json.org/ – javidrathod

1
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

2

爲了測試我已經設置了的燒瓶中應用程序的環境。爲了使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> 

輸出的樣子:

Output

+0

這是你做的很多工作,只要有可能就嘗試用代碼進行邏輯回答。可以通過查看代碼來幫助您找出問題。 – bhansa

+1

@bhansa,謝謝你的建議。我最近遇到類似的問題,同時開發一個應用usig Flask。所以,我認爲這可能有助於未來的OP從我附加的詳細代碼中獲得要點。 – arsho

+0

謝謝你。它的工作原理。我刪除了該按鈕並使用了window.onload – Ratha

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(); 
    } 
});