MVC应用程序中AJAX请求中的相对URL

时间:2013-10-23 22:19:01

标签: ajax asp.net-mvc asp.net-mvc-4

我试图弄清楚我得到的结果(见下面的ajax调用)与此帖相关:

Relative URLs in AJAX requests

以下[WORKS和[FAILS]注释的注释显示了各种有效且无效的URL。由于上面的帖子只讨论了基于文档的URL,我试图将控制器中的方法对应于文档和控制器对应文件夹进行类比。然而,下面的结果相信这个比喻。

CAS是一个运行在网站根目录下的MVC应用程序。主题是控制者。 Index,GetSubject和RegisterSubject是Subject控制器中的方法。

并非所有这些网址都可以使用。但是,我无法解释为什么另一个不这样做。

编辑:UrlHelpers。我想了解这些规则。解析MVC类型网址的规则是什么:http://[domain]/[MVC App] / [Controller] / [Method] / [params]其中params就像[p1 / p2 /。 。 ]

我没看到模式。如下所述,当调用任一方法时,文档url = [http://localhost/cas/Subject/Index]

var ajaxService = (function () {

    var ajaxGetJson = function (method, jsonIn, callback, errorCallback, controller) {
        var ajaxUrl = getSvcUrl(method, controller);
        var docUrl = document.URL; // at his point document url =  http://localhost/cas/Subject/Index

        //[WORKS] when ajaxUrl = ../GetSubject/359143 where 359143 is the id of Subject in database
        //        correctly resolves to http://localhost/cas/Subject/GetSubject/359143

        //[FAILS] when ajaxUrl = ../RegisterSubject 
        //        resolves to http://localhost/cas/RegisterSubject  <-- notice Subject controller is missing.

        //[FAILS] when ajaxUrl = /RegisterSubject --> resolves to http://localhost/RegisterSubject

        //[WORKS] when ajaxUrl = "RegisterSubject" or "RegisterSubject/
        //        resovles to http://localhost/cas/Subject/RegisterSubject

        //[FAILS] when ajaxURL = "GetSubject"/359143"
        //        resolves to http://localhost/cas/Subject/Index/GetSubject/359143

        if (method === "RegisterSubject") { //workaround for the above failure
            ajaxUrl = "http://localhost/cas/Subject/RegisterSubject";
    }

    $.ajax({
        url:  ajaxUrl, //getSvcUrl(method, controller),
        type: "GET",
        data: ko.toJSON(jsonIn),
        dataType: "json",
        contentType: "application/json",
        success: function (json) {
            callback(json);
        },
        error: function(json) {
            errorCallback(json);                
        }});
    }

    // other AJAX types omitted

    return {
        ajaxGetJson: ajaxGetJson;
    };
}

0 个答案:

没有答案