JQM如何增强动态注入的整页内容(作为重定向的结果)?

时间:2018-06-06 21:11:37

标签: jquery jquery-mobile

版本: JQM 1.4.5。

方案
当服务器端发回无效标记而不是ajax调用的预期json数据时,UI端将显示服务器端发回的任何内容(例如登录页面,系统错误页面......)

很长一段时间以来,桌面版一直很好用。现在我试图将逻辑移植到JQM,我遇到了麻烦。

症状:

(a)页面标记没有增强。 (b)样式表(在重定向的html页面中的标签中指定)未应用

代码:

$.ajax({
    type: "POST",
    dataType: "json",
    ...

    error: function (XMLHttpRequest, textStatus, errorThrown) { 
        ...
        //display whatever server sends back. 
        if (textStatus == parsererror_textStatus ) { 

            document.write(XMLHttpRequest.responseText); 
            $('#main').trigger('pagecreate');
            $('#main').enhanceWithin();
        }
    }
});

参考
我在网上搜索了很多。但它对我来说还没有成功。有什么建议?

https://www.gajotres.net/jquery-mobile-and-how-to-enhance-the-markup-of-dynamically-added-content/

jquery mobile Dynamically Injecting Pages

http://demos.jquerymobile.com/1.3.2/faq/scripts-and-styles-not-loading.html

jQuery Mobile does not apply styles after dynamically adding content

Forcing jQuery Mobile to re-evaluate styles/theme on dynamically inserted content

1 个答案:

答案 0 :(得分:0)

我最终得到了它的工作。如果它可能在将来帮助某人,请让我在这里发布答案。

  • JQM元素必须得到增强和主题化。在这个“陷阱和显示重定向响应内容”案例中,我们必须以编程方式进行;
  • 为了让#1工作,最终我们需要以编程方式将“响应内容”加载到DOM中

代码清单:

if (textStatus == parsererror_textStatus ) { displayResponseContent(XMLHttpRequest.responseText);
}

function displayResponseContent(fullResponse){
  loadIntoDOM( fullResponse);
  enhancePageMarkup();
}

//The response has to be loaded into DOM for later manipulation
function loadIntoDOM(fullResponse){
  var startIdx = fullResponse.indexOf("<body>");
  var endIdx = fullResponse.indexOf("</body>");
  var bodyTxt = fullResponse.substring(startIdx,  endIdx + 7);
  //The main thing here is to load the "body" into DOM
  var bodyDomNodes = $.parseHTML(bodyTxt, true);
  $(document.body).empty().append(bodyDomNodes);
}

//enhance the markup of dynamically added content(e.g: "page" in our case)
function enhancePageMarkup(){
  $('div[data-role=page]').trigger('pagecreate');
  $(document.documentElement).enhanceWithin();
  $('div[data-role=page]').addClass("ui-page-active");
}