JSON数据不会附加到div

问题描述 投票:0回答:2

当我运行console.log时,我可以看到JSON,我认为这个问题与我的return语句有关。

JS:

import $ from 'jquery';
import headlineData from '../JSON/headline.json';

export default class {
    constructor() {
        this.loadHeadlineData();
    }

   // ------------------- //

    loadHeadlineData() {
        let res = headlineData.d.results.map(function(obj) {
            return {
                "Name": obj.preferredname,
                "Initials": obj.initials,
                "Title": obj.jobtitle,
                "Office": obj.office
            }
        })       
        $("#headline-cont h1").append(res);   
    }

}

console.log(headlineData)

JSON:

{
    "d": {
        "results": [{
            "preferredname": "Bobson A. Dugnutt",
            "initials": "BAD",
            "jobtitle": "Coolguy",
            "office": "New York"
        }]
    }
}

HTML snippet:

<div id="headline-cont">
   <h1></h1>
</div>

console.log(JSON.stringify(headlineData.d.results)):

[{"preferredname":"Bobson A. Dugnutt","initials":"BAD","jobtitle":"Coolguy","office":"New York"}]
javascript jquery json append
2个回答
1
投票

几点:

  1. (在OP编辑之前)在filter内部,它应该是一个返回true / false的表达式。 filter接受一个数组,返回一个数组,其值为true。例如。 [1,2,3].filter( n => n % 2 === 1 );[1,3]。你想用map吗?
  2. 当我们使用append时,我们应该添加jQuery DOM对象,例如$(...).append($("<h1>"+res+"</h1>"));;你想用text()吗? (如果<h1>已经存在)如果没有,你可以改为从选择器中删除h1并使用append
  3. 目前res是一个阵列(无论使用map还是filter)。你可能想最终使用res[0].Name。但是,如果您确实想要输出整个数组/ json,请使用JSON.stringify

1
投票

使用,分隔选择器中使用的两个类

$(".headline-cont,h1")

var headlineData={
    "d": {
        "results": [{
            "preferredname": "Bobson A. Dugnutt",
            "initials": "BAD",
            "jobtitle": "Coolguy",
            "office": "New York"
        }]
    }
};
    function loadHeadlineData() {
        let res = headlineData.d.results.filter(function(obj) {
            return {
                "Name": obj.preferredname,
                "Initials": obj.initials,
                "Title": obj.jobtitle,
                "Office": obj.office
            }
        })     
       // console.log(res)
        $(".headline-cont,h1").append(JSON.stringify(res));   
    }


loadHeadlineData();
//console.log(headlineData)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="headline-cont h1"></div>
© www.soinside.com 2019 - 2024. All rights reserved.