JQuery Ajax 调用给出 404 'Resource Not Found' 错误,但正常的 URL 调用没问题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1004899/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 10:23:30  来源:igfitidea点击:

JQuery Ajax call gives 404 'Resource Not Found' Error but normal URL call is fine

jqueryasp.net-mvc

提问by Graviton

I have a weird problem when using JQuery call in my ASP.NET MVC project. I found that the Ajax call gives 404 ( resource not found error). But when I use the usual URL GET call, I can successfully call the server without any problem. Any idea why this is so?

在我的 ASP.NET MVC 项目中使用 JQuery 调用时,我遇到了一个奇怪的问题。我发现 Ajax 调用给出了 404(资源未找到错误)。但是当我使用通常的 URL GET 调用时,我可以毫无问题地成功调用服务器。知道为什么会这样吗?

This my ASP.NET MVC code

这是我的 ASP.NET MVC 代码

public class ViewRecordController: Controller
{
  public JSONResult GetSoftwareChoice(string username)
  {
     return Json(username);
  }
}

This is my JQuery code:

这是我的 JQuery 代码:

$(function() {
$("#username").click(function() {
        $.getJSON("ViewRecord/GetSoftwareChoice", {username:'123'},
    function(data) {
        alert(data);
    });
    });
});

The above JQuery gives me a 404 error. Apparently the ViewRecord/GetSoftwareChoiceis not found on server, as far as the AJAX call is concerned.

上面的 JQuery 给了我一个 404 错误。显然ViewRecord/GetSoftwareChoice,就 AJAX 调用而言,在服务器上找不到。

But if I type this in my web browser:

但是如果我在我的网络浏览器中输入:

http://myapp/ViewRecord/GetSoftwareChoice?username=123

then there is no problem.

那么没有问题。

This is very weird, indeed.

这确实很奇怪。

Just in case if you are interested, this is my route:

以防万一,如果您有兴趣,这是我的路线:

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.MapRoute(
        "Default",                                              // Route name
        "{controller}/{action}/{id}",                           // URL with parameters
        new { controller = "Home", action = "Index", id = "" }  // Parameter defaults
    );

}

Edit: I step into my code, and found that the URL call is ViewRecord/GetSoftwareChoice?username=123.

编辑:我进入我的代码,发现 URL 调用是ViewRecord/GetSoftwareChoice?username=123.

Related question: Select Element inside Form not working in JQuery

相关问题:Select Element inside Form not working in JQuery

采纳答案by Graviton

I fix this problem by using FireBug to show me the request that was generated by JQuery. To my amazement, the url generated is

我通过使用 FireBug 向我显示由 JQuery 生成的请求来解决这个问题。令我惊讶的是,生成的网址是

http://localhost/ViewRecord/ViewRecord/GetSoftwareChoice?username=123

for the JSON call:

对于 JSON 调用:

$(function() {
$("#username").click(function() {
        $.getJSON("ViewRecord/GetSoftwareChoice", {username:'123'},
    function(data) {
        alert(data);
    });
    });
});

So I just have to change the $.getJSONline to

所以我只需要将$.getJSON行更改为

$.getJSON("GetSoftwareChoice", {username:'123'},

Alternatively, use the forward slash:

或者,使用正斜杠:

 $.getJSON("/ViewRecord/GetSoftwareChoice", {username:'123'},

回答by John G

Instead of hard-coding the URL, you might want to try a UrlHelper:

您可能想尝试使用 UrlHelper,而不是对 URL 进行硬编码:

$(function() {
    $("#username").click(function() {
        var url = '<%= UrlHelper.Action("GetSoftwareChoice", "ViewRecord") %>';
        $.getJSON(url, {username: '123'}, function(data) {
            alert(data);
        });
    });
});

回答by Carl

$(function() {
    $("#username").click(function() {
        $.getJSON('<%= Url.Action("GetSoftwareChoice", "ViewRecord")%>',{username: '123'}, function(data) {
            alert(data);
        });
    });
});

回答by jwl

Use Firefox Firebug add on, and watch what request gets made by Jquery...

使用 Firefox Firebug 插件,并观察 Jquery 发出的请求......

Is it possible that the page that this Jquery runs in is in a subdirectory, in which case the request will not be relative root as the http://myapp/"typed in" url is?

这个 Jquery 运行的页面是否可能在一个子目录中,在这种情况下,请求不会像http://myapp/“输入”url那样是相对根?

Also, I am guessing the code you specified above is not actually the code you are using (which is completely reasonable, I rairly post code as-is). Because

另外,我猜您上面指定的代码实际上并不是您正在使用的代码(这是完全合理的,我通常按原样发布代码)。因为

$.getJSON("ViewRecord/GetSoftwareChoice", {username='123'},

the = sign between username and '123' is invalid JS as far as I know. So I'm betting there is some goofy detail in the the real code that is causing the problem.

据我所知,用户名和“123”之间的 = 符号是无效的 JS。所以我打赌在导致问题的真实代码中存在一些愚蠢的细节。

回答by jwl

Replace the equal sign with a colon:

用冒号替换等号:

$(function() {
$("#username").click(function() {
        $.getJSON("ViewRecord/GetSoftwareChoice", {username:'123'},
    function(data) {
        alert(data);
    });
    });
});

回答by CooperT

I also had the same problem. After using Firebug as Graviton had done, I saw that my path was wonky so I changed it to just the name of my action. Get_OrderLineis the name of my action in my controller. inv_item_idis the parameter passed to the controller action.

我也有同样的问题。像 Graviton 一样使用 Firebug 后,我发现我的路径不稳定,所以我将其更改为我的动作的名称。 Get_OrderLine是我在控制器中操作的名称。 inv_item_id是传递给控制器​​动作的参数。

// Update OrderLine data by returning a JSON result
$('#itemsddl').click(function (e) {
    var selectedItem = $(this).val();
    var actionURL = "Get_OrderLine";
    var d = "inv_item_id=" + selectedItem;
    var uom = $('#uom');
    var size = $('#size');
    var unitLbs = $('#unitLbs');
    var totalLbs = $('#totalLbs');
    var shipName = $('#shipName');
    var hazardClass = $('#hazardClass');
    var unnaNo = $('#unnaNo');
    var packingGroup = $('#packingGroup');
    var placard = $('#placard');
    var ergNo = $('#ergNo');
    $.ajax({
        cache: false,
        type: 'GET',
        url: actionURL, 
        data: d,
        datatype: JSON,
        success: function (data) {
            uom.val(data.uom);
            size.val(data.size);
            unitLbs.val(data.unitLbs);
            totalLbs.val(data.totalLbs);
            shipName.val(data.shipName);
            hazardClass.val(data.hazardClass);
            unnaNo.val(data.unnaNo);
            packingGroup.val(data.packingGroup);
            placard.val(data.placard);
            ergNo.val(data.ergNo);
        },
        error: function (xhr, ajaxOptions, thrownError) {
            alert('Failed to query item - ' + thrownError + "\n" + "Full details: " + xhr.responseText);
        }
    });
    e.preventDefault();
});

This is my action which returns a JSON result to my jQuery. The jQuery function then handles mapping from JSON to HTML. Not very pretty, but it works.

这是我的操作,它将 JSON 结果返回给我的 jQuery。然后 jQuery 函数处理从 JSON 到 HTML 的映射。不是很漂亮,但它有效。

public ActionResult Get_OrderLine(int? inv_item_id)
{
    HazmatInfoItem item = new HazmatInfoItem();
    item.itemId = "0";
    item.size = "0";
    item.unitLbs = 0;
    item.qty = 0;
    item.totalLbs = item.qty * item.unitLbs;
    item.shipName = "";
    item.hazardClass = "";
    item.unnaNo = "";
    item.packingGroup = "";
    item.placard = "";
    item.ergNo = "";

    var items = from i in hazmatRepository.GetAllItems()
                select i;

    // Get item details
    items = items.Where(i => i.INV_ITEM_ID.Contains(inv_item_id.ToString()));

    foreach (var i in items)
    {
        item.uom = i.UNIT_MEASURE_STD;
        item.size = i.INV_ITEM_SIZE;
        item.unitLbs = 1;
        item.totalLbs = item.unitLbs * item.qty;
        item.shipName = i.PAG_SHIPPING_NAME;
        item.hazardClass = i.HAZ_CLASS_CD;
        item.unnaNo = i.MSDS_ID;
        item.packingGroup = i.PACKING_CD;
        item.placard = i.PAG_PLACARD_TYPE;
    }

    return Json(item, JsonRequestBehavior.AllowGet);
}

I had originally added a new route to try to handle this, but commented it out to allow the default routing.

我最初添加了一个新路由来尝试处理这个问题,但将其注释掉以允许默认路由。

Hopefully these solutions can help someone else who has had a similar problem when trying to use .ajax with jQuery and MVC.

希望这些解决方案可以帮助在尝试将 .ajax 与 jQuery 和 MVC 一起使用时遇到类似问题的其他人。

回答by manisha pancholi

Old function :

旧功能:

function Chart() {

    var url = "../Home/Pie/";
    $.ajax({
        url: url,
        data: {},
        cache: false,
        type: "POST",
        success: function (data) {
            var chartData = data;
            createChart(chartData);
            $(document).bind("kendo:skinChange", createChart);
        },
        error: function (xhr, status, error) {
            $('#alertdialog').html(status);
            $('#alertdialog').dialog('open');
            return false;
        }
    });
}

Answers :var url = "Home/Pie/"; Removed ../ from url

答案:var url = "Home/Pie/"; 从网址中删除 ../