Method not Allowed Error in Jquery Ajax Method used

Method not Allowed Error in Jquery Ajax Method used

本文关键字:Method Ajax used Jquery Error not Allowed in      更新时间:2023-09-26

我使用jQuery Ajax方法与Asp.net MVC 3.0

我的jQuery代码是
$.ajax({
       type: "POST",
       url: "/HomePage/GetAllCategories",
       contentType: "application/json; charset=utf-8",                
       dataType: 'json',
       success: function (result) {
          alert(result);
    }
});
我的动作方法是
public JsonResult GetAllCategories()
{
     return Json(null, JsonRequestBehavior.AllowGet);
}

我得到错误

POST http://localhost:50500/HomePage/GetAllCategories 405(方法不允许)

我的调试器没有击中这个方法

您已经在控制器中创建了GET方法,并且在jquery AJAX调用中将方法类型设置为POST。

$.ajax({
       type: "GET",
       url: "/HomePage/GetAllCategories",
       contentType: "application/json; charset=utf-8",                
       dataType: 'json',
       success: function (result) {
          alert(result);
    }
});

只需在URL末尾添加"/":

 url: "/HomePage/GetAllCategories/",

好的,试试这个。我正在使用getJson调用来尝试获取相同的数据。

$.getJSON("/HomePage/GetAllCategories",        
            function(returnData) {
              alert(returnData);           
           });

在ajax调用中设置type GET

$.ajax({
       type: "GET",
       url: '@Url.Action("GetAllCategories","HomePage")' ,
       contentType: "application/json; charset=utf-8",                
       dataType: 'json',
       success: function (result) {
          alert(result);
    }
});

和行动:

[HttpGet]
public JsonResult GetAllCategories()
{
     return Json(null, JsonRequestBehavior.AllowGet);
}

如果想通过POST然后:

$.ajax({
           type: "POST",
           url: '@Url.Action("GetAllCategories","HomePage")' ,
           contentType: "application/json; charset=utf-8",                
           dataType: 'json',
           success: function (result) {
              alert(result);
        }
    });

和行动:

    [HttpPost]
    public JsonResult GetAllCategories()
    {
         return Json(null, JsonRequestBehavior.AllowGet);
    }