2016-04-28 46 views
-1

我想調用一個函數使用Ajax,但它沒有響應。不能調用函數使用ajax

這裏是代碼:

<p id="myElem" class="alert-danger" style="display:none"></p> 

<button title="Remove" data-id="@item.Book.Book_id" class="Remove btn btn-group-sm red" style="float:initial">Remove</button> 

<script type="text/javascript"> 
    $('.Remove').click(function() { 

     var myId = $(this).data('id'); 

     $.ajax({ 
      type: "POST", 
      url: '@Url.Action("Remove", "ReadingNow")?Book_id=' + myId, 
      success: function (response) { 
       $('#myElem').html(response).fadeIn('slow'); 
       $('#myElem').delay(8000).fadeOut('slow'); 
      }, 
      failure: function (response) { 

       alert("Failure"); 
      } 
     }); 
    }); 
    </script> 

和這裏的功能:

public class ReadingNowController : Controller 
{ 
[HttpGet] 
    public ActionResult Remove(int? Book_id) 
    { 
     if (User.Identity.IsAuthenticated) 
     { 
      var x = User.Identity.GetUserId(); 
      var IsExists = db.ReadingNow.Where(t => t.Book_Id == Book_id && t.User_Id == x).FirstOrDefault(); 

      if (IsExists != null) 
      { 

       db.ReadingNow.Remove(IsExists); 
       int state = db.SaveChanges(); 
       if (state == 1) 
       { 
        return Content("Book Removed From Your Reading Now List !"); 

       } 
      }     

     } 
     return Content("Error !"); 

    } 
} 

注:當我試圖直接它的工作原理調用它,但使用Ajax時我沒有得到結果。 .. 我怎麼解決這個問題?

回答

0

確保jQuery是工作

首先,確保你的jQuery代碼工作正常和引用。你需要包括調用任何jQuery的相關代碼庫以前參考:

<!-- Example Reference --> 
<script src="https://code.jquery.com/jquery-2.1.4.js"></script> 
<script> 
    $(function(){ 
      // Place your code here 
    }); 
</script> 

如果要執行GET ...

您在指定範圍內的ajax()通過type屬性調用您正在發出POST請求,但您的Controller Action明確期望GET通過[HttpGet]屬性裝飾您的操作。

您可以通過更改您的type屬性從POSTGET解決這個(或者你可以完全刪除它GET是默認):

type: "GET", 

如果要執行POST ...

或者,如果您想實際執行POST,則只需保留現有代碼並使用[HttpPost]屬性代替:

[HttpPost] 
public ActionResult Remove(int? Book_id) 
{ 
    // Code omitted for brevity 
} 
+0

同樣的問題,沒有得到結果.. –

+0

假設你做的,我提出的一個變化,它應該工作得很好。更改後,您當前的代碼是什麼樣的? –

+0

我剛剛將ajax類型更改爲GET ...這是令人困惑的,因爲當我通過url調用該方法時,它正在工作並刪除該項目! –

0

我的事情的問題是在這條線:

網址: '@ Url.Action( 「刪除」, 「ReadingNow」)Book_id =?' +身份識別碼

不要使用@ Url.Action,而不是當前語法在JS中使用剃鬚刀(您需要使用僞元素),只需寫入url [「/ ReadingNow/Remove?Book_id =」+ id]。這樣你就可以確切地知道請求會去哪裏,閱讀起來更容易。

1

您還可以通過傳遞參數(S)調用通過AjaxController,如下圖所示:

<script type="text/javascript"> 
$('.Remove').click(function() { 
    $.ajax({ 
     url: '@Url.Action("Remove", "ReadingNow")', 
     data: { myId: $(this).data('id') /* add other additional parameters */ }, 
     cache: false, 
     type: "POST", 
     success: function (response) { 
      $('#myElem').html(response).fadeIn('slow'); 
      $('#myElem').delay(8000).fadeOut('slow'); 
     }, 
     failure: function (response) { 
      alert("Failure"); 
     } 
    }); 
}); 
</script>