开发者

How do I extract a foursquare access_token saved to DOM as a link so I can use it for API calls?

开发者 https://www.devze.com 2023-03-15 13:13 出处:网络
Essentially, if I\'m in Firebug and look at the net objects I see the status 200 If I click on the JSON tab I can see my access_token, but how do I extract it from there so I can use for API calls?

Essentially, if I'm in Firebug and look at the net objects I see the status 200

If I click on the JSON tab I can see my access_token, but how do I extract it from there so I can use for API calls?

Here's the latest code tried.

var jsonUrl = url +"&callback=?";
var access_token;

$("#getJSON").click(function() {
    $.getJSON(jsonUrl, { dataType: "JSONP" }, function(json){ 
        ...
        access_token = json.access_token;
        ...
    });
});

also tried:

$.ajax({
  dataType: 'jsonp',
  jsonp: 'callback',
  url: url,
  success: function (json) {
    console.log(json.access_token);
  },
});

But when I try and alert(access开发者_开发知识库_token); or run a foursquare api call I get the following errors

Resource interpreted as Script but transferred with MIME type application/json. 

Uncaught SyntaxError: Unexpected token : checkinsGET https://api.foursquare.com/v2/users/self/checkins?oauth_token=undefined&format=json 401 (Unauthorized)

I feel like its ready and waiting for me to call it, but how on earth do I print it from the Dom into a var that I can use? Been fighting for hours and been trying all my research techniques for some reason this one's elluding me. Thanks for everyone's help so far, I'm really hoping to get passed this!


Browsers natively implement a global function JSON.parse(), and if for some reason that doesn't work you can use jQuery's parseJSON() function.

Here's how it works. Let's say your JSON object has the following format:

{
    Status: "Success",
    Resource: {
        Name: "Person's Name",
        URL: "http://blahblahblah.com/extrastuffhere?querystuff=here"}}

Then you can access the "URL" element by using JSON.parse() like so:

var url = JSON.parse(json).Resource.URL;

(I'm unfamiliar with Foursquare but it should look similar, and you can do console.log(json) to see its structure.)

So your code might look something like this:

$("#getJSON").click(function() {
    $.getJSON(jsonUrl, { dataType: "JSONP" }, function(json){ 
        var parsed = JSON.parse(json);
        console.log(parsed);
        access_token = parsed.access_token;
    });
});

Hope that helps!

0

精彩评论

暂无评论...
验证码 换一张
取 消