populate jquerymobile listview from json



我是jQuery移动开发的新手,我无法从JSON填充jQuery移动列表视图。我总是收到错误警报。

这是我的代码:

<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>listview demo</title>
        <link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.css">
        <script src="http://code.jquery.com/jquery-1.10.0.min.js"></script>
        <script src="http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.js"></script>
    </head>
    <body>
        <div data-role="page" id="index">
            <div data-role="header">
                <h1>jQuery Mobile Example</h1>
            </div>
            <div data-role="content">
                <ul data-role="listview"></ul>
            </div>
            <script type="text/javascript">   
              $(document).on('pagebeforeshow', '#index', function()
              {
                $.ajax
                ({
                      url : "http://localhost/Info.php",
                      dataType: 'json',
                      success: function (result) {ajax.jsonResult = result;alert('OK');},
                      error: function (request,error) {alert('error!');}
                 });
              });
            </script>
        </div>
    </body>
</html>

这是一个演示: http://jsfiddle.net/hungerpain/PAMY7/

以下是 HTML 的外观:

<div data-role="page" id="mypage2">
    <div data-role="header" data-theme="b">
         <h1>Listview </h1>
    </div>
    <div data-role="content"></div>
</div>

如果您只想填充列表视图一次,则可以使用pageinit事件来完成它。 如果每次到达此页面时都应该刷新,请使用 pageshowpagebeforeshow

你从这样的东西开始:

$(document).on("pageinit", "#mypage2", function () {
});

然后在这个里面,你会做一个ajax调用并设置一个这样的数组:

var typeArray = [];
//make your ajax call here and assign your JSON to typeArray variable//
//typeArray = result in your success function of ajax
typeArray = ["The Great Escape", "12 Angry Men", "Wolf of Wall Street", "Man of Steel"];

假设typeArrayajax调用的结果填充。然后设置一个ul和一个li元素,您将注入到dom中:

var $ul = $("<ul/>", { "data-role": "listview" }),  $li = $("<li/>");

然后,循环遍历typeArray并将这些元素添加到 $li ,您可以将其添加到 $ul 中。

var i = 0;
for (; i < typeArray.length; i++) {
     $li.clone().html(typeArray[i]).appendTo($ul);
}

$ul附加到标有 data-role=content<div>。在此之后,您必须像这样刷新list

$("[data-role=content]", this).html($ul).promise().done(function () {
       $("ul", this).listview().listview("refresh");
}); 

如果ajax调用抛出 error s,则必须使用错误处理程序并找出您面临的错误。将错误选项更改为:

error: function (xhr, ajaxOptions, thrownError) {
        alert(xhr.status);
        alert(thrownError);
}

并查看什么错误作为警报发出。如果这是你的问题,你必须考虑将这个问题重新标记为jQuery,因为它与jQM无关。

最新更新