将URL查询字符串传递给Javascript函数

时间:2013-11-19 01:44:55

标签: javascript php

我正在尝试将查询字符串从URL传递给Javascript函数,但我做的一切似乎都没有用。我正在使用PHP生成Javascript代码。

如果我有以下网址:

  

www.testing.com/?test=5

我希望函数输出以下代码:

"googletag.pubads().setTargeting("test","5");', 'close');"

我尝试使用echo $_GET["test"]添加PHP代码,但不是显示值,而是显示$_GET["test"]。我甚至尝试在Javascript中创建一个自定义函数来获取URL查询字符串,当我尝试显示它时,它只输出变量名称,但不输出值本身。有谁知道我做错了什么,并有想法如何解决这个问题?

以下是功能:

function google_admanager_dfp_add_js($js = NULL, $type = 'slot') {
    static $ga_js = array();

    // add the js to a type
    if (isset($js) && isset($type)) {
        $ga_js[$type][] = $js;

        //add the init and service scripts the first time this is run
        if (!isset($ga_js['service'])) {

            if (variable_get('google_admanager_dfp_useasync', FALSE)) {
                google_admanager_dfp_add_js("var googletag = googletag || {};googletag.cmd = googletag.cmd || [];", 'service');
                google_admanager_dfp_add_js("(function() {var gads = document.createElement('script');gads.async = true;gads.type = 'text/javascript';var useSSL = 'https:' == document.location.protocol;gads.src = (useSSL ? 'https:' : 'http:') + '//www.googletagservices.com/tag/js/gpt.js';var node = document.getElementsByTagName('script')[0];node.parentNode.insertBefore(gads, node);})();", 'service');

                google_admanager_dfp_add_js("googletag.cmd.push(function() {", 'pre');
                google_admanager_dfp_add_js("googletag.enableServices(); });", 'close');

            } else {
                google_admanager_dfp_add_js('(function() {var useSSL = \'https:\' == document.location.protocol;var src = (useSSL ? \'https:\' : \'http:\') +\'//www.googletagservices.com/tag/js/gpt.js\';document.write(\'<scr\' + \'ipt src="\' + src + \'"></scr\' + \'ipt>\');})();', 'service');

                // set the close script to fetch the ads.

                if (isset($_GET["test"])) {

                    // Line in question is below ->
                    google_admanager_dfp_add_js('googletag.pubads().setTargeting("test","");', 'close');
                }
                google_admanager_dfp_add_js('googletag.pubads().enableSyncRendering();googletag.enableServices();', 'close');
            }

        }
        return;
    }

2 个答案:

答案 0 :(得分:0)

您可以使用location.search获取该对,如下所示:

var query = window.location.search.substring(1);
var pair = query.split("=");

// ...
// Line in question is below ->
google_admanager_dfp_add_js('googletag.pubads().setTargeting('+pair[0]+','+pair[1]+');', 'close');

pair[0]将为testpair[1]将为5

答案 1 :(得分:0)

http://www.mathias-bank.de/2007/04/21/jquery-plugin-geturlparam-version-2/

帮助我在简单的.js文件中执行您正在寻找的内容。

信任创建它的Mathias Bank。