jQuery UI tabs: how to send ajax request with post data?

六月ゝ 毕业季﹏ 提交于 2019-12-01 19:36:38

To make the AJAX method POST, you can add a type to the ajaxOptions object. To collect data for the post, you could take advantage of jQuery.data() and then hide the POST parameters in the anchor.

<div id="tabs">
    <ul>
        <li><a href="#tabs-1">Preloaded</a></li>
        <li><a href="ajax/content1.html">Tab 1</a></li>
        <li><a href="ajax/content2.html" data-country="1" data-city="35">Tab 2</a></li>
        <li><a href="ajax/content3-slow.php">Tab 3 (slow)</a></li>
        <li><a href="ajax/content4-broken.php">Tab 4 (broken)</a></li>
    </ul>
    <div id="tabs-1">
        <p>Proin elit arcu, rutrum commodo.</p>
</div>

And the JavaScript:

var postData = {};

$("#tabs").tabs({
    select: function(event, ui) {
        postData = {
            country: parseInt($(ui.tab).data('country')),
            city: parseInt($(ui.tab).data('city'));
        };
    },
    ajaxOptions: {
        type: 'POST',
        data: postData,
        error: function(xhr, status, index, anchor) {
            $(anchor.hash).html("Couldn't load this tab. We'll try to fix this as soon as possible. " + "If this wouldn't be a demo.");
        }
    }
});

Try it: JSFiddle

If your parameters change for each link, you'll have to come up with a way to know which parameters you're looking for. You could get the index of the tab in the select() event using ui.index and use a switch to get different parameters for each case. Admittedly this solution isn't very pretty, but it could work.

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