jQuery Mobile Ajax会同时发送GET和POST请求

3

这里是问题:

默认情况下,jQuery Mobile在应用程序中使用GET请求来处理所有链接,所以我编写了一个小脚本,以便从每个链接中删除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个回答

2

不要禁用AJAX链接,你可以劫持链接的点击事件,并决定是否使用$.post()

$(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

全局配置是通过 $.mobile.config 对象来进行设置和控制的。它包含了对于整个jQuery移动框架的核心设置,例如默认的页面转场效果、页面加载时的等待图标以及Touch事件的默认触发时间和间隔时间。你可以在jQuery文档的官方网站上找到更多有关该对象的详细信息。

在你回答之前,我已经找到了问题所在 - 它是 $.mobile.ajaxEnabled = false;,所以你说得对!谢谢! - bobek

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接