简体   繁体   中英

Pass javascript url parameter to html

I've got a bit of javascript (shown below in a simplified format) which is the "ad tag" from the ad server that brings up an ad unit on the html page.

<script type="text/javascript" src="http://adserverdomain.net;pcode=1234;city=nameofcity;suburb=nameofsuburb"></script>

The javascript has more variable but I've just shown one.

Below this I have a <div> in which I'd like to pull the variable "pcode" from the above javascript and display it's value using

$('div').html("");

So the <div> needs to be populated with the value "1234".

Any idea how I can do this? Thanks

EDIT: I've updated the url (added .net and some other variables after pcode to avoid confusion). Also, I don't have access to the initial script, so I can't add an id to it. The script is generated by the ad server and it always has the variable pcode (with a different value). just need to be able to display that in another div on the same html page.

Try

<script type="text/javascript" src="http://adserverdomain;pcode=1234;city=sajdhsk;suburb=asdsadas"></script>
<div id="pcode"></div>
<div id="city"></div>
<div id="suburb"></div>

then

var pcodesrc = $('script[src^="http://adserverdomain;"]').attr('src');

$('#pcode').html(pcodesrc.match(/pcode=(.+?)(?=(;|$))/)[1])
$('#city').html(pcodesrc.match(/city=(.+?)(?=(;|$))/)[1])
$('#suburb').html(pcodesrc.match(/suburb=(.+?)(?=(;|$))/)[1])

Demo: Fiddle

or

$('#pcode').html(pcodesrc.match(/pcode=([^;]+)/)[1])
$('#city').html(pcodesrc.match(/city=([^;]+)/)[1])
$('#suburb').html(pcodesrc.match(/suburb=([^;]+)/)[1])

Demo: Fiddle

Try this with url.Actually the below code get data from url querystring.Edit it and give your url.

function getUrlVars() {
            var vars = [], hash;
            var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
            for (var i = 0; i < hashes.length; i++) {
                hash = hashes[i].split('=');
                vars.push(hash[0]);
                vars[hash[0]] = hash[1];
            }
            return vars;
        }

var me = getUrlVars()["pcode"];

Try this buddy

function getvalues()
    {
        var values = {};
        var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) { values[key] = value;});
        return values;
    }

whenever you want to use it

var value = getvalues()["pcode"];

Use this value to put in your html element

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