jQuery Ajax 网址

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4213620/
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 16:50:33  来源:igfitidea点击:

jQuery Ajax URL

jqueryajaxforms

提问by Harsha M V

I am doing an Ajax call from site.com/users/{username}

我正在从site.com/users/{username}进行 Ajax 调用

i wanna access the url site.com/account/deleteCommentbut when i check in fireBug it is trying to access site.com/users/account/deleteComment

我想访问 url site.com/account/deleteComment但是当我检查 fireBug 时它试图访问site.com/users/account/deleteComment

here is my code

这是我的代码

    $.ajax({
        url: "../account/deleteComment/" + deleteID,
        success: function () {
            $("#comment-" + deleteID).slideUp("fast");
        }
    });

回答by Pekka

Well, then ../../is going to do the trick, isn't it?

好吧,那么../../就可以解决问题,不是吗?

That said, it would probably be a good idea to use absolute URLs here.

也就是说,在这里使用绝对 URL 可能是个好主意。

  url: "/account/deleteComment/" + deleteID,

this will take away your ability to easily move your application into a sub-folder, but in most cases, that is not a problem.

这将使您无法轻松地将应用程序移动到子文件夹中,但在大多数情况下,这不是问题。

回答by Mahdi Porkar

you can use location.origin for get base address

您可以使用 location.origin 获取基地址

var deleteID;
 $.ajax({
        url:location.origin + "/account/deleteComment/" + deleteID,
        success: function () {
            $("#comment-" + deleteID).slideUp("fast");
        }
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

 $.ajax({
        url:location.origin + "/account/deleteComment/" + deleteID,
        success: function () {
            $("#comment-" + deleteID).slideUp("fast");
        }
    });

回答by Sahil Patel

Absolute URL is a good idea in ajaxbut this is more good and easy way. Just declared var siteURL = www.example.com;globally. And used this in every ajaxrequest like below.

绝对 URL 是一个好主意,ajax但这是更好、更简单的方法。刚刚var siteURL = www.example.com;在全球宣布。并在每个ajax请求中使用它,如下所示。

<script>
$.ajax({
    url: siteURL + '/path/to/file',
    type: 'POST',
    data: {param1: 'value1'},
});
</script>

Generally, I declared in main index file or config of JS file.

通常,我在主索引文件或 JS 文件的配置中声明。

回答by Jón Trausti Arason

Change the URL to:

将网址更改为:

/account/deleteComment/

That way it'll go to the root path:

这样它就会转到根路径:

site.com/account/deleteComment

回答by DazManCat

I've just had a similar problem in one of my apps.
The solution I used was

我刚刚在我的一个应用程序中遇到了类似的问题。
我使用的解决方案是

$.url("Config/GetEnvironment")

Which ever directory I am in the URL is rendered correctly.

我在 URL 中的哪个目录被正确呈现。