如何使用 JSON 数据填充 jQuery Mobile ListView? [英] How to populate a jQuery Mobile ListView with JSON data?

查看:25
本文介绍了如何使用 JSON 数据填充 jQuery Mobile ListView?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在这里使用 HTML 和 jQuery Mobile (JQM) 开发一个 web 应用程序,所以我对此很陌生.我在这里尝试做的是用名称列表填充 JQM 列表视图.这些姓名中的每一个都将链接到显示个人数据(全名、地址、出生日期等)的新页面.

目前,由于我缺乏知识,我为每个人手动创建了一个新的 .html 文件(例如,johnDoe.html 用于虚构人物 Mr. John Doe).然后我通过函数将列表元素物理链接到这个 html 文件.

问题是现在我有 100 多个人来填充该列表视图.我认为有一种更简单的方法可以做到这一点,而不是为所有这些个人手动创建 100 多个 html 文件,对吗?

我听说过这个 JSON 东西可能会奏效,但我有零计算知识的背景,我不太了解它是如何工作的.有人可以解释一下我该怎么做吗?

非常感谢!

我正在使用 Dreamweaver CS5.5 进行编码.对于我负责开发的这个 web 应用程序,我得到了一个模板"或使用 JQM 和 Backbone.js 的排序.因此,不知何故,单个 HTML 文件的多页"结构似乎不起作用.从我在模板中看到的内容来看,每个 HTML 文件都有一个相应的 JS 文件,其代码如下所示:

define(['jquery','下划线','骨干','帮手','浏览量/份/列表','文本!模板/vpr2.html'],函数 ($,_,骨干,帮手,phrListView,tmpVpr2) {var view = Backbone.View.extend({过渡:'淡入淡出',反向:真实,初始化:函数(){this.phrlistview = new phrListView();},渲染:函数(){$(this.el).append(_.template(tmpVpr2, {}));console.log("渲染子元素...");Helper.assign(这个,{'#phrListView':this.phrlistview});返回 this.el;}});返回视图;});

对于 HTML 页面,它们都以

标记开头,然后是

,在以 <div data-role=footer> 结尾之前,所有内容都在开始和结束标记中.

对于我有问题的列表视图,列表视图的 JQM 代码将位于 HTML 文件的 <div data-role=content> 部分.那么如何使用 JSON 数据填充此列表视图?

(如果我在这方面听起来非常菜鸟,我深表歉意,因为我确实是 >.<非常感谢您的帮助!)

解决方案

解决方案

是的.可以有两页,其中一页用于显示您的数据,另一页用于显示单击项目的详细信息.我不得不引入一些旧东西,我在 jQM 1.1 版本时制作的一个演示并将其更改为现代.无论如何,考虑到我有一个这样的数组:

<预><代码>[{身份证":0,年龄":31,"name": "Avis Greene",性别女","公司": "握手","email": "avisgreene@handshake.com","电话": "+1 (845) 575-2978","address": "518 Forrest Street, Washington, New York, 3579"},{身份证":1,年龄":31,"name": "邓恩海恩斯","性别": "男","company": "Signity","email": "dunnhaynes@signity.com","电话": "+1 (829) 454-3806","address": "293 Dean Street, Dante, Oregon, 5864"}]

我随机生成了一些东西,并使其多达 100 个元素,就像你看起来的那样.我有两页.

<div data-role="page" id="info-page"><div data-role="header" data-theme="b"><h1>信息

<div data-role="内容"><ul data-role="listview" id="prof-list" data-divider-theme="a" data-inset="true"><li data-role="list-divider" data-theme="b" role="heading">名称</li>

<!--第二页--><div data-role="page" id="details-page"><div data-role="header" data-theme="b"><a href="#" data-rel="back" data-role="button">返回</a><h1>员工详情</h1>

<div data-role="content"></div>

第一页,#info-page 用于在列表视图中显示数据.第二页 #details-page 是点击项目的信息.这就是你所需要的.只有两个页面,不多不少. 所以每次点击发生时,你都通过 JavaScript 执行以下操作

  • 从数组中获取数据的当前值.就像单击列表中的第 4 个 li 一样,从包含所有数据的数组中获取第 4 个对象.
  • 存储在第二页的data变量中,方便以后检索.像这样:

    $("#details-page").data("info", info[this.id]);

  • 然后,使用changePage重定向到第二页,像这样:

    $.mobile.changePage("#details-page");

  • 当第二个页面打开时,使用 pagebeforeshow 事件从页面中获取数据(当点击上一页中的标记时,您存储到此页面中的数据.

  • 使用一些 HTML 布局来填充数据.我使用了 jQM 的网格.

就是这样!

完整代码

我附上了与 HTML 一起使用的 JS.它的自我解释.阅读代码中的内联注释,您将能够了解更多.假设 info 是图中的数组.

//第一页的pageinit事件//只触发一次//编写所有与 page1 相关的加载函数和事件处理程序$(document).on("pageinit", "#info-page", function () {//设置用于添加<li/>的字符串var li = "";//要添加$li的容器$.each(info, function (i, name) {//添加<li>到li"变量//注意变量中+=的使用//意味着我要添加到现有数据中.不更换它.//将索引值存储在数组中作为<a>的id标签li += '<li><a href="#" id="' + i + '" class="info-go">'+ name.name + '</a></li>';});//将列表附加到ul$("#prof-list").append(li).promise().done(function () {//等待追加完成 - 这就是你使用promise()的原因//done() 将在追加完成后运行//为#details-page添加重定向发生的点击事件$(this).on("click", ".info-go", function (e) {e.preventDefault();//将信息存储在下一页的数据中$("#details-page").data("info", info[this.id]);//将页面#更改为第二页.//现在地址栏中的URL将读取index.html#details-page//其中#details-page是第二页的id"//我们现在将使用changePage()方法重定向到那个$.mobile.changePage("#details-page");});//刷新列表以增强其样式.$(this).listview("刷新");});});//使用pagebeforeshow//不要使用PAGEINIT!//原因是你希望每次都发生这种情况//pageinit 只会发生一次$(document).on("pagebeforeshow", "#details-page", function () {//从数据中获取 - 当在上一页中单击a"时,您将其放在这里var info = $(this).data("info");//将HTML放入的字符串var info_view = "";//使用 for..in 遍历对象for (var key in info) {//我在这里使用网格布局.//使用任何你想要的布局.//key是对象中属性的key//如果 obj = {name: 'k'}//键=名称,值=kinfo_view += '<div class="ui-grid-a"><div class="ui-block-a"><div class="ui-bar field" style="font-weight :粗体;文本对齐:左;">'+ key + '</div></div><div class="ui-block-b"><div class="ui-bar value" style="width : 75%">'+ info[key] + '</div></div></div>';}//将此添加到html$(this).find("[data-role=content]").html(info_view);});

演示

我还制作了一个演示,您可以在 jsfiddle.net 上阅读更多相关信息.这是链接:http://jsfiddle.net/hungerpain/52Haa/

I'm developing a webapp here using HTML and jQuery Mobile (JQM), so I'm pretty new at this. What I'm trying to do here is to populate a JQM listview with a list of names. Each of this names will link to a new page with personal data being displayed (Full name, address, date of birth, etc).

Currently, because of my lack of knowledge, I manually create a new .html file for EACH individual person (e.g. johnDoe.html for a fictional character Mr. John Doe). I then physically link the list elements to this html file via the function.

Problem is now I have 100 over individuals to populate that list view. I think that there's an easier way to do this rather than manually creating 100+ html files for all these individual persons right?

I heard of this JSON thing that might do the trick, but coming from a background of ZERO computing knowledge, I don't really understand how it works. Will someone please shed some light on how can I do this?

Thanks a lot!

EDIT: I'm using Dreamweaver CS5.5 to do the coding. For this webapp that I'm tasked to develop, I was given a "template" or sorts that uses JQM and Backbone.js. As such, somehow the "multi-page" structure for a single HTML file doesn't seem to work. From what I see in the template, every HTML file has a corresponding JS file that has code that looks like this:

define(['jquery',
        'underscore',
        'backbone',
        'helper',
        'views/phr/list',
        'text!templates/vpr2.html'
    ],
    function ($,
        _,
        Backbone,
        Helper,
        phrListView,
        tmpVpr2) {
        var view = Backbone.View.extend({
            transition: 'fade',
            reverse: true,
            initialize: function () {
                this.phrlistview = new phrListView();
            },
            render: function () {

                $(this.el).append(_.template(tmpVpr2, {}));

                console.log("Rendering subelements...");
                Helper.assign(this, {
                    '#phrListView': this.phrlistview
                });

                return this.el;
            }

        });

        return view;
    });

For the HTML pages, they all begin with a <div data-role=header> tag, then a <div data-role=content>, before ending with a <div data-role=footer>, all with their respective content within the opening and closing tags.

For my listview in question, the JQM code for the listview will be within the <div data-role=content> part of the HTML file. How can I populate this listview with JSON data then?

(Apologies if I sound extremely noob at this, because I really am >.< Really appreciate the help!)

解决方案

Solution

Yes. Its possible to have two pages and use one for displaying your data and one to show up the details of the clicked item. I had to pull in some old stuff, a demo I made when jQM was in version 1.1 and change it to modern times. Anyway, considering I have an array like this :

[
    {
        "id": 0,
        "age": 31,
        "name": "Avis Greene",
        "gender": "female",
        "company": "Handshake",
        "email": "avisgreene@handshake.com",
        "phone": "+1 (845) 575-2978",
        "address": "518 Forrest Street, Washington, New York, 3579"
    },
    {
        "id": 1,
        "age": 31,
        "name": "Dunn Haynes",
        "gender": "male",
        "company": "Signity",
        "email": "dunnhaynes@signity.com",
        "phone": "+1 (829) 454-3806",
        "address": "293 Dean Street, Dante, Oregon, 5864"
    }
]

I randomly generated stuff and made it upto 100 elements, just like how you seem to have. I have two pages.

<!--first page -->
<div data-role="page" id="info-page">
    <div data-role="header" data-theme="b">
         <h1> Information</h1>

    </div>
    <div data-role="content">
        <ul data-role="listview" id="prof-list" data-divider-theme="a" data-inset="true">
            <li data-role="list-divider" data-theme="b" role="heading">Names</li>
        </ul>
    </div>
</div>
<!--second page -->
<div data-role="page" id="details-page">
    <div data-role="header" data-theme="b"><a href="#" data-rel="back" data-role="button">Go back</a>

         <h1>Employee Details</h1>

    </div>
    <div data-role="content"></div>
</div>

The first page, #info-page is for showing data in a listview. The second page, #details-page is for the info of the clicked item. Thats all you need. Only two pages, not more than that. So every time a click happens, you do the following through JavaScript

  • Get the current value of data from the array. Like if you click on the 4th li in the list, get the 4th object from the array which has all the data.
  • Store it in the data variable of the second page, so that it can be retrieved later. Something like this:

    $("#details-page").data("info", info[this.id]);
    

  • Then, redirect to second page using changePage, like this :

    $.mobile.changePage("#details-page");
    

  • When the second page opens, use the pagebeforeshow event to get the data from the page (which you stored into this page when the tag in the previous page was clicked.

  • Use some HTML layout to populate the data. I used jQM's grids.

That's all folks!

Full code

Ive attached the JS used with the HTML. Its self explanatory. Read the inline comments in the code and you'll be able to understand more. Assume info is the array in picture.

//pageinit event for first page
//triggers only once
//write all your on-load functions and event handlers pertaining to page1
$(document).on("pageinit", "#info-page", function () {


    //set up string for adding <li/>
    var li = "";
    //container for $li to be added
    $.each(info, function (i, name) {
        //add the <li> to "li" variable
        //note the use of += in the variable
        //meaning I'm adding to the existing data. not replacing it.
        //store index value in array as id of the <a> tag
        li += '<li><a href="#" id="' + i + '" class="info-go">' + name.name + '</a></li>';
    });
    //append list to ul
    $("#prof-list").append(li).promise().done(function () {
        //wait for append to finish - thats why you use a promise()
        //done() will run after append is done
        //add the click event for the redirection to happen to #details-page
        $(this).on("click", ".info-go", function (e) {
            e.preventDefault();
            //store the information in the next page's data
            $("#details-page").data("info", info[this.id]);
            //change the page # to second page. 
            //Now the URL in the address bar will read index.html#details-page
            //where #details-page is the "id" of the second page
            //we're gonna redirect to that now using changePage() method
            $.mobile.changePage("#details-page");
        });

        //refresh list to enhance its styling.
        $(this).listview("refresh");
    });
});

//use pagebeforeshow
//DONT USE PAGEINIT! 
//the reason is you want this to happen every single time
//pageinit will happen only once
$(document).on("pagebeforeshow", "#details-page", function () {
    //get from data - you put this here when the "a" wa clicked in the previous page
    var info = $(this).data("info");
    //string to put HTML in
    var info_view = "";
    //use for..in to iterate through object
    for (var key in info) {
        //Im using grid layout here.
        //use any kind of layout you want.
        //key is the key of the property in the object 
        //if obj = {name: 'k'}
        //key = name, value = k
        info_view += '<div class="ui-grid-a"><div class="ui-block-a"><div class="ui-bar field" style="font-weight : bold; text-align: left;">' + key + '</div></div><div class="ui-block-b"><div class="ui-bar value" style="width : 75%">' + info[key] + '</div></div></div>';
    }
    //add this to html
    $(this).find("[data-role=content]").html(info_view);
});

Demo

I've also made a demo where you can read more about this at jsfiddle.net. Here's the link : http://jsfiddle.net/hungerpain/52Haa/

这篇关于如何使用 JSON 数据填充 jQuery Mobile ListView?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆