2011-12-28 106 views
3

这里的问题是: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谢谢你

回答

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"); 

会工作得很好。

您也可以关闭全球AJAX联通过结合mobileinit事件是这样的:

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

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

+0

我没有你的答案之前,找出问题 - 这是'$ .mobile.ajaxEnabled = false;'所以你说得对!谢谢! – 2011-12-28 19:58:28