js”;脚本”;为XMLHttpRequest调用预先设置的文件夹名称

js "scripts" folder name prepended to XMLHttpRequest calls

本文关键字:设置 文件夹 调用 脚本 XMLHttpRequest js      更新时间:2023-09-26

我在Web服务器的"scripts"文件夹中有一个名为myscripts.js的javascript文件。它可以通过以下方式访问:

http://www.example.com/scripts/myscripts.js

myscripts.js中有一个javascript函数,它对我的网站的somemethod.html进行XMLHttpRequest调用。这是呼叫代码:

xmlhttp.open("GET","somemethod.html",false);

99%的时间一切都很好。但我发现一些浏览器正在为调用准备"scripts/"。结果是这样的调用:

http://www.example.com/scripts/somemethod.html

什么时候应该是这样的:

http://www.example.com/somemethod.html

这是一个自定义的Web服务器(即,我基本上处理所有请求)。

  1. 我的网络服务器应该能够处理这个问题吗?或者这只是一个我不应该担心的侥幸浏览器
  2. 我不应该在javascript中使用"相对"路径吗?而是在java脚本中使用绝对调用?例如:它应该像这样编码:,而不是"somemethod.html"

    xmlhttp.open("GET"http://www.example.com/somemethod.html",false);

在JavaScript中使用相对路径是绝对好的(绝大多数是实践标准),只需注意它们与的相对关系即可:您在其中包含JavaScript的文档(而不是JavaScript文件)。您似乎对此很清楚,但只是强调而已。

我从未见过浏览器出现这种错误。你看到的请求可能来自一个写得不好的网络爬虫,它在查看JavaScript的来源,而不是做一些智能的事情,比如弄清楚它在哪里/如何运行。

不过,只是为了清楚起见,关于相对的事情(更多的是为了潜伏者而不是你):

给定这种结构:

foo.htmlindex.htmljs/script.js

在该结构中,如果在index.html:中包含script.js

<script src="js/script.js"></script>

然后使用该脚本文件中的代码执行XHR调用,该调用将相对于正常运行的浏览器上的index.html,而不是script.js

我从不使用相对请求,我构建了自己的url,并使用js代码来构建和传递url,使用"toString"方法来提供我所需的url。

顺便说一句,尽量不要再使用同步XHR调用,理想情况下应该使用异步和回调,这很痛苦,但这是最好的。

client . open(method, url [, async = true [, username = null [, password = null]]])
    Sets the request method, request URL, and synchronous flag.
    Throws a "SyntaxError" exception if either method is not a valid HTTP method or url cannot be parsed.
    Throws a "SecurityError" exception if method is a case-insensitive match for `CONNECT`, `TRACE` or `TRACK`.
    Throws an "InvalidAccessError" exception if async is false, the JavaScript global environment is a document environment, and either the timeout attribute is not zero, the withCredentials attribute is true, or the responseType attribute is not the empty string. 

来源:http://xhr.spec.whatwg.org/#the-打开%28%29方法