2015-12-02 107 views
0

想要向azure市場進行查詢。 API認證是空的用戶密碼。返回應該是一個json對象。下面的代碼將「[object Object]」返回給瀏覽器。我的錯誤在哪裏?Ajax使用auth獲取json文件

<script> 
    $.ajax({ 
    type: 'GET', 
    url: 'https://api.datamarket.azure.com/Bing/SearchWeb/v1/Web?Query=%keyword%27', 
    dataType: 'json', 
    beforeSend: function (xhr) { 
     xhr.setRequestHeader('Authorization', make_base_auth("", "myaccountkeyhere")); 
    }, 
    success: function (data) { 
     JSON.stringify(data, null, 4); 
     document.write(data); 
     console.log(data); 
     } 
    }); 

    function make_base_auth(user, password) { 
     var tok = user + ':' + password; 
     var hash = btoa(tok); 
     return 'Basic ' + hash; 
    } 

回答

0

的問題是你document.writing JSON對象。
您需要:

 
var jsonString = JSON.stringify(data, null, 4); 
document.write(jsonString); 
console.log(jsonString); 

我做了一個快速的jsfiddle這一點。請注意,jsfiddle不允許document.write,但替換您的密鑰,你應該看到它的工作。

jsfiddle for loading bing search via json

function make_base_auth(user, password) { 
    var tok = user + ':' + password; 
    var hash = btoa(tok); 
    return 'Basic ' + hash; 
} 

function writeToDom(title, content) { 
    $("#results").append("<div class='header'>" + title + ":</div><div><pre>" + content + "</pre></div>"); 
} 

function showResults(evnt) { 

    $.ajax({ 
    type: 'GET', 
    url: 'https://api.datamarket.azure.com/Bing/Search/v1/Composite?Sources=%27web%27&Query=%27keyword%27', 
    dataType: 'json', 
    beforeSend: function (xhr) { 
     xhr.setRequestHeader('Authorization', make_base_auth("", "YOURKEYHERE")); 
    }, 
    success: function (data) { 
     var search = JSON.stringify(data, null, 4); 
     writeToDom('Json', search); 
     alert(search); 
     console.log(search); 
     } 
    }); 
} 

$(function() { 
    $(document).on("click", "#clickme", showResults); 
}); 
+0

謝謝!現在工作。 – Stefan