【问题标题】:Populating pages using ajax data within jquery-mobile not always working在 jquery-mobile 中使用 ajax 数据填充页面并不总是有效
【发布时间】:2019-06-09 21:49:01
【问题描述】:

我在链接中使用 url 变量来传递唯一 ID,该 ID 通过 ajax 运行并使用 .html() 注入。见下面的代码

我添加了一个超时,在填充之前将empty()添加到div中,

页面链接:

<a href="member.html?id=' + member.id + '" data-role="none" data-transition="slide">

页面创建:

$(document).on( "pageshow", "#member-page", function(event) {
   .....
   var request = $.ajax({
      url: serviceURL + 'member_profile',
      method: "GET",
      data: { id : id },
      dataType: "html"
   });
   request.done(function( data ) {
      ...
      alert(html);
      $('#member-profile').hide().empty().html(html).fadeIn();
    });


    request.fail(function( jqXHR, textStatus, errorThrown ) {
       alert( "Request failed Line 752: " + textStatus + " - " + jqXHR.responseText);
       $.mobile.loading( "hide" );
    });
});

有时有效,有时无效。尽管alert(html) 总是显示数据。

有没有更好的方法来传递 id 和渲染页面,比如使用pagebeforecreate

【问题讨论】:

  • 请参考这个答案:stackoverflow.com/a/15464607/4845566
  • 此解决方案将 $("#home").on("pageshow", function( event) { 更改为 $(document).on("pageshow", "#home", function( event ) { 但我已经有后一种格式的了。
  • 您的member.html 文件中不是带有member-page iddiv 吗?

标签: jquery jquery-mobile phonegap


【解决方案1】:

您没有向我们展示您的代码中最重要的部分。如果您还包含 $.ajax 部分,那么分析您的代码会容易得多。

我会假设两种可能的解决方案,而且我认为这两种解决方案在您的情况下是相互交织的。

  • Ajax 进程本质上是异步的,这意味着其余代码不会等待它完成。这可能是您有时会看到新内容而有时看不到的原因。大概和AJAX调用的速度有关。

你有没有试过这样做:

$.ajax({
  url: "YOUR ENDPOINT"
}).done(function(html) {
  $('#member-profile').hide().empty().html(html).fadeIn();
});

这种方式只有在实际接收到内容时才会被清理/填充。

  • 第二种可能性是pageshow 事件本身。根据其速度,jQuery Mobile 可能有时间也可能没有时间来预渲染新的 HTML 内容并显示它。如果是这种情况,最好使用 pagebeforecreate 或 pagecreate 事件。如果您使用的是旧的 jQuery Mobile 事件,或者 pageinit。

【讨论】:

  • 我添加了ajax调用,奇怪的是alert(html)总是显示数据,所以可能是div还没有渲染?我什至在填充 div 之前尝试了 2 毫秒的超时。
  • 您是否尝试过使用其他页面事件来代替 pageshow?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-28
  • 1970-01-01
  • 1970-01-01
  • 2016-05-09
相关资源
最近更新 更多