将变量传递给外部文件

时间:2014-11-20 12:48:47

标签: javascript php

这是我想要做的。我的file.php中有一个函数,它加载外部文件。我想将用户的ID添加到URL。此脚本加载文件的内容:

public function setExternalSolutionScriptsToBuffer() {
    // Get dictionary   
    $externalSolutions = file_get_contents($this->getExternalTargetingSolutionsJsUrl());

    // Composer the ouput buffer
    $this->outputBuffer .= "\n";
    $this->outputBuffer .= $externalSolutions;
    $this->outputBuffer .= "\n";
}

还有一个ID功能:

public function setExposureOfUserIdScriptToBuffer() {
    $user_id = $this->visitor->getOnlineId();
}

我需要的是将该变量传递给外部文件,并将其附加到此脚本的src URL的末尾:

(function () {
    if (location.protocol.substr(0,5)==='http:') {
        try {
            (function () {
                var d = document;
                var e = d.createElement('script');
                e.type = 'text/javascript';
                e.src = 'http://example.com/some.js?uid=' + ***user_id***;
                e.async = true;
                (d.head || d.body || d.firstChild).appendChild(e);
            })();
        } catch (e) {}
    }
})();

因此,变量将添加到URL中,src看起来像“http://example.com/some.js?uid=4234234324

1 个答案:

答案 0 :(得分:0)

快速而又脏 - 假设$ externalSolutions是JS的src

$userID = 1234;
$externalSolutions = file_get_contents(..js-file..);
$externalSolutions = str_replace('***user_id***', $userID, $externalSolutions);
echo "<script>\n",$externalSolutions,"\n</script>\n";