简体   繁体   中英

Making an ajax call from a file that's included in many pages

I'm making a simple call from a file that's included in various pages.

$.post( "wp-content/themes/biagetti_studio/inc/HandleBackground.php", {color:color} );

The problem is that i thought that the call was relative to path of the file that include the js (all the files that are including the js are in the same directory), but i discovered that it's relative to the current path, so that if i'm in localhost/biagettistudio then the script calls localhost/biagettistudio/wp-content/themes/biagetti_studio/inc/HandleBackground.php but if i'm in localhost/biagettistudio/projects it calls localhost/biagettistudio/projects/wp-content/themes/biagetti_studio/inc/HandleBackground.php .

i know i could put an absolute path

$.post( "/wp-content/themes/biagetti_studio/inc/HandleBackground.php", {color:color} );

but this presents a problem if i have to port the site were the base directory is not the root. What am i obviously missing here?

you could use

<script type="text/javascript">
    <?php
    echo "var theme_dir ='" . get_theme_root() . ‘/’ . get_template() ."';";
    ?>
</script>

in footer.php (so it's available on every page) and you wouldn't have to worry about breaking stuff if you port the site.

You can then call the script like this...

$.post( theme_dir + "/biagetti_studio/inc/HandleBackground.php", {color:color} );

how about this:

var path = location.pathname.match(/(.*)\/wp-content\/.*/)[1];
$.post( path + "/wp-content/themes/biagetti_studio/inc/HandleBackground.php", {color:color} );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM