0

this is a really simple question so please don't make fun... I have been given a URL of a webservice that will provide me with a JSON object. I wish to use jQuery's getJSON Method, for example...

var myObj = $.getJSON("https://www.myurl/");

However this isn#t working as when I use console.log(myObj.toSource()) I just seem to get a lot af JavaScript written to the console and not my object. I know I can add a callback with this method, should I do something like this:

var thisJsonObj;

$.getJSON("https://www.myurl/", function(result){
    thisJsonObj = result;

});

console.log(thisJsonObj.toSource());

This doesn't work either... where am I going wrong? The URL is working and correct.

2
  • 1
    if it's cross-domain call, try jsonp instead of json in jquery. remember to add "callback" in your server-side code. Jquery will never make cross-domain call with json only, but you can write your own Ajax function to avoid this limitation. Commented May 11, 2012 at 12:20
  • your call to console.log is executed immediately after the http request is initiated, however your callback won't be getting called until the http request is finished, so thisJsonObj is not set by the time console.log is called. If you move the console.log call into the callback you should see the correct result Commented May 11, 2012 at 12:38

2 Answers 2

2

Ajax works asynchronously, so you have to work with the JSON object inside the callback function:

var thisJsonObj;
$.getJSON("https://www.myurl/", function(result) {
    thisJsonObj = result;
    console.log(thisJsonObj);
});

Moreover, if you use external webservice, you should consider that the request should be treated as JSONP. So check if your URL has somewhat like "callback=?".

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

Comments

0

While the URL may be the URL of the webservice, are you suppose to call a function inside the webservice? For instance, if you had a python microframework (such as Flask in my example) and I wanted to get a list of items to display in a combo-box, my python might look a little like:

@app.route('/_gest_list.json')
def get_list():
    #return list of jsonified items

Which is called in your jQuery like

$.getJSON("/get_list.json", {}, function(data) {
    //Do something
});

Think of it as if I'm calling the function get_list() which is mapped to the url of the webservice/server and has the alias of /get_list.json

Also if you are working with ASP.Net to access the data you must write something like (variable name).d. All JSON data in ASP.Net is wrapped within d!

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.