0

我是 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>
4

1 回答 1

1

这是一个演示: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"];

假设它typeArray由您的ajax调用结果填充。然后设置一个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到用<div>标记的data-role=content。在此之后,您必须list像这样刷新:

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

注意

如果您的ajax调用正在抛出errors,那么您必须使用错误处理程序并找出您面临的错误。将您的错误选项更改为:

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

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

于 2013-06-20T02:58:49.200 回答