0

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!

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Is it possible to add another string after? So after apikey, I could continue the URL?
@user1658756 Yes, just append with + operator
Okay so it'd be $.getJSON('http://api.websiteexample.com/' + apikey + 'foo');. That'll appear as api.websiteexample.com/123456789foo, right?
@user1658756 exactly.. It should be like that.. you should try it out.
1

Try it this way

var apikey="123456789";

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

foo(apikey);

1 Comment

So you can pass the apikey as a parameter to the function. It can be called anything you want. It allows your function to be resuable because it will work the same way if your api key changes.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.