Loading JSON-encoded AJAX content into jQuery UI tabs

天大地大妈咪最大 提交于 2019-12-03 12:55:31

You can use the dataFilter option of the ajax call to convert your json response to the html you want to be inserted in to the panel of the tab.

Something like this:

$('#mytabs').tabs({
    ajaxOptions: {
        dataFilter: function(result){
            var data = $.parseJSON(result);
            return data.myhtml;
        }
    },
}); 

If you JSON response looked like this:

{"myhtml":"<h1>hello<\/h1>"}

I had to add:

this.dataTypes=['html']

to get this to work.

In context:

      ,ajaxOptions: {
    dataFilter: function(result,type){
      var data = $.parseJSON(result);
       // Trick jquery to think that it's html
       this.dataTypes=['html']
       return '<p>'+data.credential.id+'</p>';
    }
    ,error: function( xhr, status, index, anchor ) {
      $( anchor.hash ).html( i18n.AJAXError + ' (' + status + ')' );
    }
  }

I got stuck with this problem recently, so just in case someone has been looking for help with this kind of issue more recently, I thought it would be useful to re-open this discussion. I'm working with jQuery 1.8.2 and jQuery UI 1.9.2. I found the best way to do this with the latest version of jQuery UI was to return false from the beforeLoad event handler and send a getJSON request with the URL specified in the relevant tab.

HTML markup:

    <div id="tabs">

        <ul>
            <li><a href="/json/tab1.json">Tab 1</a></li>
            <li><a href="/json/tab2.json">Tab 2</a></li>
            <li><a href="/json/tab3.json">Tab 3</a></li>
        </ul>

    <div>

Tabs invocation code:

    $(function () {
        $("#tabs").tabs({
            beforeLoad: function (event, ui) {
                var url = ui.ajaxSettings.url;
                $.getJSON(url, function (data) {
                    ui.panel.html(data.text);
                });
                return false;
            }
        });
    });

When the beforeLoad handler returns false, the normal functionality of displaying the HTML retrieved from the URL defined in the tab is disabled. However, you still have access to the event and ui objects passed to the beforeLoad handler. You get the URL from the tab with this syntax ui.ajaxSettings.url and then display the data returned by the getJSON request as shown in the Content via Ajax example:

ui.panel.html(data.text);

In my case, it's data.text because the JSON I'm retrieving contains two properties header and text.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!