通过AJAX成功方法在html中显示数据

时间:2015-09-06 07:46:36

标签: jquery python html ajax flask

我正在编写以下代码,用于以json格式从数据库返回的html表中显示数据

<form id="register" name="register" method="post">
<input id="submitLogin" type="submit" value="Abschicken" onclick="register()">
</form>


<script type="text/javascript" charset="utf-8">


function register() {
 $.ajax({
url: 'http://XXX.de/api/user/register/?username=xxx@test.de&email=xxx@test.de&nonce=d60besdfee&display_name=xxx@test.de&user_pass=rtzrtzrtz0&apikey=gfhrtzh465&callback=?',
type: "POST",
dataType: 'json',
success: function(data){

 }
 });
}

</script>

JSON中的数据格式如下:

success : function(data){
            alert("declaring variable");
            var output="<table id=tableStyle>";
            alert("creating output");
            output+="<tr>" + "<th>" + "REPORTSUITE_ID" + "</th>" + "<th>" + "REPORTSUITE_NAME" + "</th>" + "<th>" + "STAGING_DATABASE" + "</th>" + "<th>" + "DWH_DATABASE" + "</th>" + "</tr>";
            alert("starting for loop"); 
            for (var i in data)
            {
                output+="<tr>" + "<td>" + data[i].REPORTSUITE_ID + "</td>" + "<td>" + 
      "<button>"+data[i].REPORTSUITE_NAME + "</button>" +
      "</td>" + "<td>" + data[i].STAGING_DATABASE + "</td>" + "<td>" + data[i].DWH_DATABASE + "</td>" + "</tr>";
            }
            output+="</table>";
            alert ("displaying now ");
            document.getElementById("placeholder").innerHTML=output;
          }

当我执行上面的代码时,我得到如下结果:

[{"DWH_DATABASE": "abc", "REPORTSUITE_ID": 51, "REPORTSUITE_NAME": "C1","STAGING_DATABASE": "def", "TRANS_TABLE": "T1"}, 
{"DWH_DATABASE": "abc", "REPORTSUITE_ID": 49, "REPORTSUITE_NAME": "C2", "STAGING_DATABASE": "def", "TRANS_TABLE": "T2"}, 
{"DWH_DATABASE":"abc", "REPORTSUITE_ID": 40, "REPORTSUITE_NAME": "C3", "STAGING_DATABASE": "def", "TRANS_TABLE": "T3"}]

请告诉我如何正确显示数据

2 个答案:

答案 0 :(得分:0)

代码是正确的,但要确保数据变量实际包含数据。事先通过控制台打印出来,你会看到里面的内容:

console.log("data:" + data);

答案 1 :(得分:0)

你必须首先解析json,这样你就可以使用以下代码作为对象而不是文本处理它作为成功方法的第一行:

data = JSON.parse(data);