与我相关的问题有很多,但我花了几个小时研究不同的答案并自己试验后,仍然无法解决我的问题!
我正在使用 OAuth 2.0 协议(protocol)来访问 Box 的 API。到目前为止,我已经能够检索到授权码,现在我正在尝试用它换取访问码。到目前为止一切似乎都工作正常:在我向 Box 发出 POST 请求后,我被重定向到 https://www.box.com/api/oauth2/token并收到一个我不知道如何处理的 JSON 响应。
我尝试过使用 JQuery 的 $.get 和 $.parseJSON 函数,但我完全不知道我应该如何构建代码,或者我是否一开始就以正确的方式处理这个问题。
这是我用于 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();
}
当我调用它时,我被重定向到 https://www.box.com/api/oauth2/token我的浏览器显示以下字符串:
{"access_token":"H97GnkuWCRUxxx"expires_in":3600,"refresh_token":"cIJyyyyym1aSuNFmmC2PgTtiP2xfXm0dCmzzzz,"token_type":"bearer"}
我非常感谢能得到的任何帮助,非常感谢!
最佳答案
你不需要jquery来做到这一点,事实上这很简单。
var json = JSON.parse(the returned json var);
那么你可以这样处理:
json.access_token; //this would be the access token
这是我用于 POST/GET 请求的代码:
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;
}
}
};
关于javascript - 使用 Javascript 处理 JSON 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16286060/