jquery mobile ajax发送GET和POST请求

时间:2011-12-28 15:02:04

标签: ajax asp.net-mvc-3 jquery jquery-mobile

问题在于:

默认情况下,jQuery Mobile对应用程序中的所有链接使用GET请求,因此我将这个小脚本从每个链接中删除。

$('a').each(function () {
   $(this).attr("data-ajax", "false");
});

但我有一个寻呼机,其中我实际上想要使用AJAX。寻呼机链接使用HttpPost请求进行控制器操作。所以我评论了上面的jQuery代码,以便我可以实际使用AJAX。

问题是,当我点击链接时,发出了两个请求,一个是HttpGet - 这是jQuery Mobile AJAX默认值(我不想要),第二个是HttpPost我真的想要工作。当我有上面的jQuery代码工作时,AJAX完全关闭,它只是转到URL并重新加载窗口。

我正在使用asp.net MVC 3.谢谢

1 个答案:

答案 0 :(得分:2)

您可以劫持链接点击并决定是否使用$.post(),而不是禁用AJAX链接:

$(document).delegate('a', 'click', function (event) {

    //prevent the default click behavior from occuring
    event.preventDefault();

    //cache this link and it's href attribute
    var $this = $(this),
        href  = $this.attr('href');

    //check to see if this link has the `ajax-post` class
    if ($this.hasClass('ajax-post')) {

        //split the href attribute by the question mark to get just the query string, then iterate over all the key => value pairs and add them to an object to be added to the `$.post` request
        var data = {};
        if (href.indexOf('?') > -1) {
            var tmp  = href.split('?')[1].split('&'),
                itmp = [];
            for (var i = 0, len = tmp.length; i < len; i++) {
                itmp = tmp[i].split('=');
                data.[itmp[0]] = itmp[1]; 
            }
        }

        //send POST request and show loading message
        $.mobile.showPageLoadingMsg();
        $.post(href, data, function (serverResponse) {

            //append the server response to the `body` element (assuming your server-side script is outputting the proper HTML to append to the `body` element)
            $('body').append(serverResponse);

            //now change to the newly added page and remove the loading message
            $.mobile.changePage($('#page-id'));

            $.mobile.hidePageLoadingMsg();
        });
    } else {
        $.mobile.changePage(href);
    }
});

上面的代码要求您将ajax-post类添加到要使用$.post()方法的任何链接。

总的来说,event.preventDefault()对于停止事件的任何其他处理非常有用,这样您就可以对事件做任何想法。如果您使用event.preventDefault(),则必须将event声明为其所在函数的参数。

您的代码中也不需要.each()

$('a').attr("data-ajax", "false");

工作得很好。

您还可以通过绑定到mobileinit事件来全局关闭AJAX链接:

$(document).bind("mobileinit", function(){
    $.mobile.ajaxEnabled = false;
});

来源:http://jquerymobile.com/demos/1.0/docs/api/globalconfig.html