Javascript jQuery AJAX 请求中的相对与绝对 url

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

Relative vs. absolute urls in jQuery AJAX requests

phpjavascriptjqueryajax

提问by fresskoma

I'm having a hard time getting my AJAX requests to work on a staging server. It all worked fine on my development machine, but as soon as I uploaded it, all my AJAX requests stopped working. I found out that, if I change the relative urls (eg. "index.php") to absolute urls ("http://example.com/index.php") the requests work again, but I do not understand why.

我很难让我的 AJAX 请求在登台服务器上工作。在我的开发机器上一切正常,但是一旦我上传它,我所有的 AJAX 请求就停止工作。我发现,如果我将相对网址(例如“index.php”)更改为绝对网址(“ http://example.com/index.php”),请求会再次工作,但我不明白为什么。

Example request:

示例请求:

jQuery.post('index.php', {id: 1234, action: 1, step: 1}, function(data) { /* something */ });

This does not work, I does not even show up in the firebug console. The success handler is called though, which is very confusing.

这不起作用,我什至没有出现在萤火虫控制台中。尽管调用了成功处理程序,这非常令人困惑。

This works just fine:

这工作得很好:

jQuery.post('http://example.com/index.php', {id: 1234, action: 1, step: 1}, function(data) { /* something */ });

Can anybody explain why AJAX requests behave in this way? x_X

谁能解释为什么 AJAX 请求会以这种方式运行?x_X

回答by Sampson

Try adding a /before index.phpin your first example to force it to look from root. Double check to make sure your directory-structures are exactlythe same with regards to where index.phpis.

尝试在您的第一个示例中添加/beforeindex.php以强制它从根目录查看。仔细检查以确保您的目录结构与 where完全相同index.php

回答by dalemac

IF you are using URL routing, for example in an MVC framework, it will always be relative to the page the execution runs through, which does not necessarily match the URL in your address bar.

如果您使用 URL 路由,例如在 MVC 框架中,它将始终与执行运行的页面相关,它不一定与地址栏中的 URL 匹配。

Consider the following file structure:

考虑以下文件结构:

mysite/index.php
mysite/resources/javascript/my_javascript.js
mysite/resources/css/my_css.css

Usually, MVC frameworks route all page requests through a single file, such as index.php, ( http://www.mysite.com/index.php). This makes it easy to use relative urls because resources and scripts will always be in the same relative path. Javascript will always be in /resources/javascript/ CSS will always be in /resources/css/

通常,MVC 框架通过单个文件路由所有页面请求,例如 index.php ( http://www.mysite.com/index.php)。这使得使用相对 url 变得容易,因为资源和脚本将始终位于相同的相对路径中。Javascript 将始终在 /resources/javascript/ 中 CSS 将始终在 /resources/css/ 中

no matter what is in the browser address bar. It could be:

无论浏览器地址栏中是什么。它可能是:

http://www.mysite.com/index/
http://www.mysite.com/kittens/
http://www.mysite.com/kittens/cute/
http://www.mysite.com/kittens/fluffy/
etc..

回答by Ben

This is an old post, so I'm sorry to drag it out. But it was obviously relevant to my problem and it was a top result on Google.

这是一个旧帖子,所以我很抱歉把它拖出来。但这显然与我的问题有关,并且是 Google 上的最佳结果。

After some experimenting with the exact same problem I've determined the answer.

在对完全相同的问题进行了一些试验后,我已经确定了答案。

No matter where you are running the script from, the requested file is relative to /

无论您从何处运行脚本,请求的文件都是相对于 /

For example, in my file structure I have a folder named js. Under it is my ajaxProcess.js file. The xml file i was trying to read was located in the same directory, so following standard rules it made sense for the url of the ajax call to simply be url: 'myfile.xml' however, this did not work.

例如,在我的文件结构中,我有一个名为 js 的文件夹。在它下面是我的 ajaxProcess.js 文件。我试图读取的 xml 文件位于同一目录中,因此按照标准规则,ajax 调用的 url 只是 url: 'myfile.xml' 是有意义的,但是,这不起作用。

After some playing around I placed my xml in / and ran the ajax again. Vuala!

经过一番玩耍后,我将我的 xml 放在 / 中并再次运行 ajax。哇啦!

Some more playing around, and I discovered it doesn't matter where you call the js from at all, it will still default to /

再玩一些,我发现从哪里调用 js 并不重要,它仍然会默认为 /

I ended up placing my xml in a folder 'xml' and now the following ajax will work from anywhere:

我最终将我的 xml 放在一个文件夹“xml”中,现在以下 ajax 可以在任何地方工作:

$.ajax({
        type:'get',
        dataType: 'xml',
        url: 'xml/class.xml',
        success: function(xml){
            $(xml).find('class').each(function(){
                //code here
            })
        }
    });

回答by RB_

I think that the best way to avoid this kind of problems is to set up a config file for javascripts in the head of your HTML. You can include something like that in page head:

我认为避免此类问题的最佳方法是在 HTML 的头部为 javascripts 设置一个配置文件。您可以在页眉中包含类似的内容:

<script>
        var url = "http:\/\/www.yourdomain.com\/application";
        var path = "\/path\/on\/server\/to root folder";
</script>

Another approach is to attach these variables to window object:

另一种方法是将这些变量附加到 window 对象:

 <script>
window.myUrl = "http:\/\/www.yourdomain.com\/application";
...
    </script>

So, later on you can use these variables inside js files:

因此,稍后您可以在 js 文件中使用这些变量:

jQuery.post( url+'/index.php', {id: 1234, action: 1, step: 1}, function(data) { // something });

script in the header can be auto-generated, based on your app config, so when app is deployed url and path variables are changed accordingly.

标题中的脚本可以根据您的应用程序配置自动生成,因此在部署应用程序时,url 和路径变量会相应更改。