jQuery UI tabs: how to send ajax request with post

2020-04-09 05:31发布

问题:

From jQuery UI tabs:

<script>
$(function() {
    $( "#tabs" ).tabs({
        ajaxOptions: {
            error: function( xhr, status, index, anchor ) {
                $( anchor.hash ).html("Couldn't load this tab.");
            }
        }
    });
});
</script>


<div class="demo">

<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">Tab 2</a></li>
    </ul>
    <div id="tabs-1">
        <p>Proin elit arcu, rutrum commodo.</p>
</div>

How to send ajax request with post data in this case (maybe through ajaxOptions).

I do not know how to modify tabs urls to send post data, for example:

<li><a href="ajax/content1.html(country:1,city:35)">Tab 1</a></li>
<li><a href="ajax/content2.html(code:'aa')">Tab 1</a></li>

Thanks!

EDITED:

In jQuery it's:

$.load("some_url",{country: countryValue});

So I have post header (country) and post value (countryValue). How to do the same with each tab?

回答1:

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.