如何获取执行的javascript文件目录?

时间:2018-04-09 21:50:29

标签: javascript php jquery ajax wordpress

我在以下目录中有一个javascript文件:

/httpdocs/wp-content/themes/themeName/users/js

我想在这个目录中创建一些PHP文件:

/httpdocs/wp-content/themes/themeName/users

如何在Javascript / Jquery中获取PHP文件目录?

1 个答案:

答案 0 :(得分:0)

如果您在页面上引用了文件(例如,在<head>中)

<head>
    <script src="~/httpdocs/wp-content/themes/themeName/users/js/test-file.js"></script>
</head>

你可以将文件名(没有.js扩展名)和它的文件夹名称一起传递给这个函数,它应该返回删除了文件夹名称的路径:

$(function () {
    var getFilePath = function (fileName, scriptFolderName) {
        var reg = new RegExp("" + fileName + ".*\\.js");
        var regReplace = new RegExp("/" + scriptFolderName + "/" + fileName + ".*\\.js.*$");
        // Find the file in the page
        var fileSrc = $("script[src]").filter(function () {
            return reg.test($(this).attr("src"));
        }).first();

        if (0 === fileSrc.length) {
            console.log("Could not get location of " + fileName + ".js");
        } else {
            // Return the path without parent folder
            return fileSrc.attr("src").replace(regReplace, "/");
        }
    };
    // Call the function with the referenced filename and folder
    // (the function could be adjusted to remove the need for the 
    // folder name, by hardcoding it, but this is more flexible)
    var filePath = getFilePath("test-file", "js");
    console.log("filePath: : " + filePath);
});