问题是这样的:
默认情况下,jQuery Mobile 对应用程序中的所有链接使用 GET 请求,因此我使用这个小脚本将其从每个链接中删除。
$('a').each(function () {
$(this).attr("data-ajax", "false");
});
但是我有一个寻呼机,我实际上想在其中使用 AJAX。寻呼机链接使用 HttpPost
请求来执行 Controller 操作。所以我注释了上面的 jQuery 代码,以便我可以实际使用 AJAX。
问题是,当我单击链接时,会发出两个请求,一个是 HttpGet - 这是 jQuery Mobile 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");
会很好地工作。
您还可以通过绑定(bind)到 mobileinit
事件来全局关闭 AJAX 链接,如下所示:
$(document).bind("mobileinit", function(){
$.mobile.ajaxEnabled = false;
});
来源:http://jquerymobile.com/demos/1.0/docs/api/globalconfig.html
关于ajax - jquery mobile ajax同时发送GET和POST请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8657460/