javascript - 无法从本地 json 绑定(bind)数据来查看 polymer 2

标签 javascript data-binding polymer iron-ajax

我正在使用 Polymer 2,并且想要绑定(bind)本地 json 文件中的数据。但每次我尝试它都无法仅获取 json 文件。

我尝试过两种方法来实现它:

1) 使用

<iron-ajax url="data/employees.json" handle-as="json" last-response="{{items}}" auto>
</iron-ajax>

文件夹结构:

folder Structure

<iron-list items="{{items}}" as="item">
    <template>
        <div class="item">
            <b>[[item.nickname]]</b>
            <p>[[item.phone]]</p>
        </div>
    </template>
</iron-list> 

我还导入了iron-ajax和iron-list

2)使用$.get从start中的json中提取数据并将其放入变量中以将其绑定(bind)到 View 。

<script>
    class IronListClass extends Polymer.Element {
        static get is() {return 'iron-comp'}

        ready() {
            super.ready();
            var that = this;
            // $.get('data/employees.json', function(data) {
            //     that.employees = $.parseJSON(data).results;
            //     console.log(that.employees);
            // });
            $.get('data/employees.json', function(data) {
            this.employees = $.parseJSON(data).results;
            console.log(this.employees);
            }.bind(this));
        }        
    }
    window.customElements.define(IronListClass.is, IronListClass);
</script>

也尝试过那个=这个。

最佳答案

您可以按照以下示例加载 json 文件,因为它已经在我的应用程序中运行。

   <iron-ajax 
            auto 
            url$="{{url}}" 
            handle-as="json" 
            last-response="{{loadedItems}}"
           >
    </iron-ajax>

...

     static get properties() { return { 
        url :{
            type:String,
            value() {return "./data/employees.json"; }
        }

...

    static get observers() { return ['checkJsonFileLoaded(loadedItems)']}

    checkJsonFileLoaded(j) {
       if (j) {
           this.set('items', j);
           console.log(items); //u should see the loaded json file. If so than the problem is iron-list (to publish the result)
       }
    }

关于javascript - 无法从本地 json 绑定(bind)数据来查看 polymer 2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48006684/

相关文章:

android - 如何使用数据绑定(bind)滚动到 ScrollView 上的位置?

c# - WPF DataContext 在看似相同的情况下工作方式不同

polymer - 如何在 Polymer 2.0 中的 span 元素上设置监听器?

javascript - 在 polymer 中使用 core-ajax 和 xml 构建新元素

javascript - Angular promise .finally() 被乱序调用

javascript - WebMethod 无法在 ASP.Net Web 角色(Web 表单)中工作?

c# - WPF 中的数据绑定(bind) (C#)

svg - Polymer.js是否支持内部SVG元素?

javascript - 如何控制变量提升?

javascript - Adobe AIR JavaScript 中使用 MouseCursorData 的 native 光标