无法使用ajax调用函数

我正在尝试使用ajax调用函数,但它没有响应。

这是代码:

$('.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"); } }); });

这是function:

  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时我没有结果……我怎样才能解决这个问题?

确保jQuery正在运行

首先,确保您的jQuery代码正常工作并被引用。 调用任何与jQuery相关的代码之前 ,您需要包含对库的引用:

    

如果你想进行GET ……

您在ajax()调用中指定您正在通过type属性发出POST请求,但您的Controller Action明确期望通过[HttpGet]属性装饰您的操作来GET

您可以通过将type属性从POST更改为GET来解决此问题(或者您可以完全删除它,因为GET是默认值):

 type: "GET", 

如果你想执行POST

或者,如果您想要实际执行POST ,那么只需保留现有代码并使用[HttpPost]属性:

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

您也可以通过传递参数来调用Controller ,如下所示:

  

我的问题在于这一行:

url:’@ Url.Action(“删除”,“ReadingNow”)?Book_id =’+ myId

不要使用不是当前语法的@ Url.Action在JS中使用razor(你需要使用伪元素),只需写入url [“/ ReadingNow / Remove?Book_id =”+ id]。 这样你就可以确定请求的去向,更容易阅读。