JQuery relative and absolute path

I need to define this path in jquery, in fact I have one file called functions.js and inside this one function for the download url with jquery

The problem is that the js download in the website index and the file are really in a subfolder

<script src="http://www.domain.com/wp-content/includes/themes/mytheme/js/functions.js"></script> 

Js called in the website index is in wp-content / includes / themes / mytheme / js

And loading jquery calls: wp-content / includes / themes / mytheme / index_loader.php

I can put the absolute path in index_loader.php in jquery, but my question is: if possible, do not use this and calculate the path in js file

Actually:

 $("#test").load("http://www.domain.com/wp-content/includes/mytheme/index_loader.php"); 

Maybe this or calculate the internal jquery file? - I try and do not work .....

 $("#test").load("../index_loader.php"); 

This is my problem, thanks,

+4
source share
2 answers

The way JavaScript works, which it loads from the file from which it was called, and now the file in which it was written.

To do what you need, you need to provide a relative path from the current page you are viewing.

Example:

If the current page is http://www.domain.com , then you will need to do:

 $("#test").load("wp-content/includes/mytheme/index_loader.php"); 

If the current page is http://www.domain.com/wp-content/index.php , then you will need to do:

 $("#test").load("includes/mytheme/index_loader.php"); 

As a side note, CSS is not the same path, and CSS relative path is based on the file in which it was written.

+4
source

It's too late...
but I use this method, and I just add it here if someone needs it in the future:
I had this problem when trying to use the same load statement from pages that exist in different URLs (different parts of the site).

you can use location js variable

location returns the current path
e.g. wwww.blog.mysite.com/posts/postn25/comment64

location.origin returns the domain and host (so the root of the site)
for the previous URL, it will be
wwww.blog.mysite.com/posts/postn25/comment64

so when you do

 $('#my_tag').load(`${location.origin}/mypath/mypage`) 

it will always look for /mypath/mypage , starting from the root directory, so even if the domain changes, it will still work

PS: (unrelated) Today I found out that you can use> * to load everything that is inside a tag in another, for example:

 $('#my_tag').load(`${location.origin}/mypath/mypage #my_tag > *`) 

will load all the HTML from #my_tag, which exists in /mypath/mypage , into #my_tag on the current page

0
source

Source: https://habr.com/ru/post/1491566/


All Articles