jquery mobile ajax发送GET和POST请求

这是问题所在:

默认情况下,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.谢谢

您可以劫持链接上的点击并决定是否使用$.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