2011-12-28 200 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