简体   繁体   中英

Handling JSON response with Javascript

There are tons of questions related to mine, but after spending several hours poring over different answers and experimenting on my own, I still can't solve my problem!

I'm using the OAuth 2.0 protocol to gain access to Box's API. So far I've been able to retrieve an authorization code, and right now I am trying to trade it for an access code. Everything seems to be working fine so far: after I make a POST request to Box, I get redirected to https://www.box.com/api/oauth2/token and receive a JSON response that I have no idea how to deal with.

I've tried using JQuery's $.get and $.parseJSON functions but I have no idea how I'm supposed to structure the code at all or if I'm approaching this the right way in the first place.

Here is the function I'm using to POST:

function post_to_url(path, params) {

    var form = document.createElement("form");
    form.setAttribute("method", "post");
    form.setAttribute("action", 'https://www.box.com/api/oauth2/token');

    for(var key in params) {
        if(params.hasOwnProperty(key)) {
            var hiddenField = document.createElement("input");
            hiddenField.setAttribute("type", "text");
            hiddenField.setAttribute("name", key);
            hiddenField.setAttribute("value", params[key]);

            form.appendChild(hiddenField);
         }
    }

    document.body.appendChild(form);
    form.submit();
}

And when I call it, I get redirected to https://www.box.com/api/oauth2/token and my browser shows the following string:

{"access_token":"H97GnkuWCRUxxx"expires_in":3600,"refresh_token":"cIJyyyyym1aSuNFmmC2PgTtiP2xfXm0dCmzzzz,"token_type":"bearer"}

I truly appreciate any help I can get, thanks so much!

You do not need jquery to do this, it's very simple in fact.

var json = JSON.parse(the returned json var);

Then you can handle it like this:

json.access_token; //this would be the access token

Here is the code I use for POST/GET requests:

    var xhr=new XMLHttpRequest();
    xhr.open('POST','url', true);//the true bool makes it async
    xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded"); //this url encodes the request (this is for if you have special values such as spaces and symbols)
    xhr.send(information to send goes here);
    xhr.onreadystatechange=function()
    {
        if(xhr.readyState===4)
        {
            if(xhr.status===200)
            {
                var json = xhr.responseText;
            }
        }
    };

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