[英]Javascript XML Http request using the Google Custom Search Element api
我正在開發一個利用Google搜索API的Chrome擴展程序,以從ajax請求返回圖像。 顯然,該api已不再起作用,所以我想知道如何使用自定義搜索元素Api發出類似的請求。 我已經在下面發出了請求的代碼部分粘貼了。
var logo = function (searchTerm, callback, message, name) {
var searchUrl = 'https://ajax.googleapis.com/ajax/services/search/images' +
'?v=1.0&q=' + encodeURIComponent(searchTerm);
var x = new XMLHttpRequest();
x.open('GET', searchUrl);
// The Google image search API responds with JSON, so let Chrome parse it.
x.responseType = 'json';
x.onload = function() {
// Parse and process the response from Google Image Search.
var response = x.response;
if (!response || !response.responseData || !response.responseData.results ||
response.responseData.results.length === 0) {
console.log( "loading error" )
console.log(response)
console.log(response.responseData)
console.log(response.responseData.results)
}
var firstResult = response.responseData.results[0];
// Take the thumbnail instead of the full image to get an approximately
// consistent image size.
var imageUrl = firstResult.tbUrl;
var width = parseInt(firstResult.tbWidth);
var height = parseInt(firstResult.tbHeight);
console.assert(
typeof imageUrl == 'string' && !isNaN(width) && !isNaN(height),
'Unexpected respose from the Google Image Search API!');
callback(imageUrl, width, height, message, name);
};
x.onerror = function() {
alert("error")
document.writeln("network error");
};
x.send();
}
我一直在嘗試通過閱讀文檔來解決問題 ,但是我絕對可以使用一些幫助。
這是文檔的鏈接: 使用REST 。
您需要在Google Developer Console上創建自己的自定義搜索引擎,並相應地修改getImageUrl()
方法。
更改searchUrl
var searchUrl = 'https://www.googleapis.com/customsearch/v1?' +
'key=' + 'YOUR_KEY' +
'&cx=' + '00000:yourcx' +
'&searchType=image' +
'&q=' + encodeURIComponent(searchTerm);
並根據JSON修改response
對象。
您可以參考此問題以了解如何調整控制台和優化搜索結果。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.