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

JQM How to Enhance a full page content that is being dynamically injected (as result of redirect)?

版本: JQM 1.4.5。

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

长期以来桌面版一直运行良好。现在我正在尝试将逻辑移植到 JQM 中,但我遇到了麻烦。

症状:

(a) 页面标记未增强。 (b) 样式 sheet(在重定向的 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

我终于成功了。如果将来可能对某人有所帮助,请让我 post 在这里回答。

  • JQM 元素必须得到增强和主题化。在这种 "trap & display redirect response content" 情况下,我们必须以编程方式进行;
  • 为了让#1 工作,最终发现我们需要以编程方式将 "response content" 加载到 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");
}