Ajax仅在刷新页面后从javaScript获取数据并加载菜单

时间:2015-10-23 04:42:11

标签: javascript jquery ajax

$('#subregionListPage').bind('pageinit', function(event){


    var output = $('#subregions');
    var region = getUrlVars()["reg"];
    $.ajax({
        url: 'http://localhost:8888/my/getsubregions.php',
        dataType: 'jsonp',
        cache: false,
        data: {reg: region},
        jsonp: 'jsoncallback',
        timeout: 5000,
        success: function(data, status){
            var out = '';
            $.each(data, function(i,item){ 
                out += '<li><a href="subregions.html">' + item.subregion.capitalize() + '</a></li>';
            });

            output.append(out);
            output.trigger('create');
            output.listview('refresh');

        },

        error: function(){
            output.text('There was an error loading the data.');
        }
    });
});

String.prototype.capitalize = function() {
    return this.charAt(0).toUpperCase() + this.slice(1);
}

function getUrlVars() {
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}

所以这段代码的问题在于它创建列表不是在页面最初加载之后,但是在加载和刷新之后,我尝试了很多东西,但没有一个工作。 此外,这是调用脚本的html代码。

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/jquery.mobile-1.4.5.min.css">
<script src="js/jquery-1.11.3.min.js"></script>
<script src="js/jquery.mobile-1.4.5.min.js"></script>
</head>

<body>

<div id="subregionListPage" data-role="page">
    <script src="getsubregions2.js"></script>
    <div data-role="header" data-position="fixed">
        <h1>Select Sub Region</h1>
    </div>
    <div data-role="content">
         <ul id='subregions' data-role="listview"></ul>
    </div>      
</div>

</body>
</html>

建议后更新了代码:

    $(document).on('pagecreate', '#subregionListPage', function(event){

    var output = $('#subregions');
    $.ajax({
        url: 'http://localhost:8888/my/getsubregions.php',
        dataType: 'jsonp',
        cache: false,
        data: {reg: $.urlParam('reg')},
        jsonp: 'jsoncallback',
        timeout: 5000,
        success: function(data, status){        
            var out = '';
            $.each(data, function(i,item){ 
                out += '<li><a href="subregions.html">' + item.subregion.capitalize() + '</a></li>';
            });


            output.append(out);
            output.trigger('create');
            output.listview('refresh');

        },

        error: function(){
            output.text('There was an error loading the data.');
        }
    });
});

String.prototype.capitalize = function() {
    return this.charAt(0).toUpperCase() + this.slice(1);
}

$.urlParam = function(name){
    var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
    if (results==null){
       return null;
    }
    else{
       return results[1] || 0;
    }
}

2 个答案:

答案 0 :(得分:1)

以下是您的代码究竟发生了什么:

方案

  • 第一次加载页面时,DOM中没有元素#subregionListPage。并且在元素被渲染之前,在元素上附加pageinit事件的处理程序。
  • 下次重新加载页面时,由于事件处理程序以前已附加到pageinit上的#subregionListPage事件,处理程序将被触发。

引自jQuery's docs regarding .bind()

  

处理程序附加到jQuery对象中当前选定的元素,因此在调用.bind()时, 元素必须存在

.bind()是jQuery实现中的旧方法(在1.0版中添加)。它没有.on()方法那么灵活,因为使用.on()可以将事件处理程序附加到当前甚至不存在于DOM 中的元素。

这可以通过将事件处理程序附加到超级父级(例如document)来实现,并且当特定子元素触发事件时,事件会传播( bubbles )到那个父母。最终,当事件到达时,在子项上下文中附加到父项的事件处理程序将被触发。

解决方案

将您的.bind()替换为on()

$(document).on('pageinit', '#subregionListPage', function(event){
   /* ... */
}

注意:从jQuery v1.4开始,不推荐使用pageinit事件。在这种情况下使用的推荐事件是pagecreate

更新

正如所指出的,你有一个脚本,你绑定pagecreate事件,在div内必须在创建时触发它:

<div id="subregionListPage" data-role="page">
     <script src="getsubregions2.js"></script>
     <!-- rest of your HTML -->

这里发生的是,在HTML的 inital 加载中,div #subregionListPage存在,但是它的事件绑定没有 - 因为这需要的Javascript代码是尚未运行,并且没有注册处理程序来捕获它触发的pagecreate事件。

将脚本移动到HTML的<head>,这样您的JS就可以在第一次加载页面时准备好绑定#subregionListPage的特定处理程序。

答案 1 :(得分:0)

您是否尝试将代码放入$(document).ready(function(){})中,如果是,则尝试在成功函数后设置警报,看看警报是否适用于页面加载。