简体   繁体   English

从ajax调用返回JSON到HTML div

[英]Return JSON from ajax call into HTML div

I've got my javascript ajax call returning json and I'm trying to put it on the HTML page. 我有返回json的javascript ajax调用,并且试图将其放在HTML页面上。

I use this code: 我使用以下代码:

      success: function(response) {
        console.log(response);
        for (var i=0;i<response.length;++i)
        {
            $('#main').append('<div class="name">'+response[i].name+'</>');
        }
          },
          error: function(response) {
            alert(response);
          }
        });

However it seems to print json to my console just fine but I dont get anything returned to the website. 但是,它似乎可以将json打印到我的控制台上,但是我什么也没回到网站。

I have a div to collect it in: 我有一个div将其收集在:

<div id="main">Test</div>

Any idea where I am going wrong? 知道我要去哪里错了吗?

EDIT: The console log response is this: 编辑:控制台日志响应是这样的:

{totalPages: 0, firstPage: true, lastPage: true, numberOfElements: 0, number: 0, …}
columns: {columnIds: Array(3)}
firstPage: true
lastPage: true
number: 0
numberOfElements: 0
oberonRequestXML: [null]
oberonResponseXML: [null]
summaryData: {totals: Array(3)}
totalElements: 0
totalPages: 0
__proto__: Object

As explained in comments, your JSON response is not an array -- there is no length property, so your loop does not loop. 如评论中所述,您的JSON响应不是数组-没有length属性,因此您的循环不会循环。 Moreover, you seem to expect an array with objects that have a name attribute. 此外,您似乎期望数组包含具有name属性的对象。 This is nowhere to be seen in the response you get. 您收到的回复中无处可见。

Assuming you are calling the right JSON service, the only information you can iterate over is stored in two attributes: columns.columnIds and summaryData.totals . 假设您呼叫的正确的JSON的服务,您可以遍历的唯一信息存储在两个属性: columns.columnIdssummaryData.totals So you would get something , if you code it like this: 因此,如果您这样编写代码,您将得到一些东西

console.log(response);
for (var i=0;i<response.columns.columnIds.length;++i) {
    $('#main').append('<div class="name">'
                 + response.columns.columnIds[i] 
                 + ': '
                 + response.summaryData.totals[i] + '</div>');
}

This assumes that these values are primitive values, which is not clear from the response you got. 假定这些值是原始值,从您得到的响应中还不清楚。

But again, this will not output name property values, as they do not appear in your JSON as far as is visible in your question. 但是同样,这不会输出name属性值,因为它们不会在您的问题中显示在JSON中。

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

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