Javascript最佳实践:从函数中的不同位置调用文件

时间:2022-03-31 15:59:37

I have a problem with a javascript file that includes a function. I have 2 files, that include the javascript file and that included function. The structure could look this way for example:

我有一个包含函数的javascript文件的问题。我有2个文件,包括javascript文件和包含的功能。结构可以这样看,例如:

/var/www/file1.jsp
/var/www/content/file2.jsp

both include the file include.js with the function doSomething() The function is calling another file that is located on the server via GET. For example the file is located in /var/www/index.jsp

两者都包含文件include.js和函数doSomething()函数通过GET调用位于服务器上的另一个文件。例如,该文件位于/var/www/index.jsp中

How would be the best way to call the index.jsp out of the function with a relative path (absolute pathes are not possible in this context). The problem is that file1.jsp and file2.jsp have a different context from which they include the .js file and so the current path for the function is different in both cases.

如何使用相对路径从函数中调用index.jsp的最佳方法(在此上下文中不可能使用绝对路径)。问题是file1.jsp和file2.jsp有一个不同的上下文,它们包含.js文件,因此在两种情况下函数的当前路径都不同。

1 个解决方案

#1


0  

Assuming index.jsp is always in the same place, I would parse the absolute url from window.location.href and construct my path the index.jsp right there in doSomething()

假设index.jsp总是在同一个地方,我会解析来自window.location.href的绝对url并在doSomething()中构建我的路径index.jsp

EDIT:

A better way would be to let the browser do the url parsing for you . Use window.location.hostname and then concatenate with the hard-coded path to index.jsp relative to the root directory of your domain. Feed that concatenated string to your GEt request and all should be well.

更好的方法是让浏览器为您解析url。使用window.location.hostname,然后使用相对于域根目录的index.jsp的硬编码路径进行连接。将连接字符串提供给您的GEt请求,一切都应该很好。

#1


0  

Assuming index.jsp is always in the same place, I would parse the absolute url from window.location.href and construct my path the index.jsp right there in doSomething()

假设index.jsp总是在同一个地方,我会解析来自window.location.href的绝对url并在doSomething()中构建我的路径index.jsp

EDIT:

A better way would be to let the browser do the url parsing for you . Use window.location.hostname and then concatenate with the hard-coded path to index.jsp relative to the root directory of your domain. Feed that concatenated string to your GEt request and all should be well.

更好的方法是让浏览器为您解析url。使用window.location.hostname,然后使用相对于域根目录的index.jsp的硬编码路径进行连接。将连接字符串提供给您的GEt请求,一切都应该很好。