2013-04-29 129 views
1

有很多與我的問題有關的問題,但花了幾個小時仔細研究不同的答案並單獨進行實驗之後,我仍然無法解決我的問題!用Javascript處理JSON響應

我使用OAuth 2.0協議訪問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"} 

我真的感謝我能得到的任何幫助,非常感謝!

+0

JSONP可能?是在一個函數內?你也可以訪問爲 var object = _json_response_; object [「access_token」]或object.access_token。如果它是一個JSONP在jQuery中有一個特定的功能... – ncubica 2013-04-29 18:57:13

回答

2

你不需要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; 
      } 
     } 
    }; 
+0

感謝您的答案。我的問題是,我不知道如何收集json var。當我發佈POST請求時,我會重定向到一個網站,如下所示:http://i.imgur.com/W9Q1roF.png。此時,我通過POST請求寫入的任何代碼都不會被觸發。我猜測必須有一種方法來封裝POST請求到一個變量來存儲JSON對象,但我不知道如何。再次感謝您的幫助! – user2066880 2013-04-29 19:06:30

+1

@ user2066880我添加了一個示例帖子請求 – Zachrip 2013-04-29 19:12:27

+1

@ user2066880你這樣做的方式將帶你到另一個頁面,我這樣做的方式是通過ajax請求。 – Zachrip 2013-04-29 19:15:13