简体   繁体   中英

How to include a variable in a function - Javascript

Ok, so I have a variable that contains some information that needs to go in a function. For example, if I have;

var apikey="123456789";

function foo() {
    $.getJSON('http://api.websiteexample.com/ + apikey');
}

I'm looking to add some information that is stored in a variable to the end of a website address when requestion JSON data.

Is there way I've done in the example correct?

Thanks!

Try like below,

//Note the quotes moved -----------------v
$.getJSON('http://api.websiteexample.com/' + apikey);

When you have it inside quotes.. It would be considered as a string . You need to put it outside quotes for it to know it is an variable.

Try it this way

var apikey="123456789";

function foo(key) {
    $.getJSON('http://api.websiteexample.com/ ' + key);
}

foo(apikey);

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