Javascript 来自chrome扩展的多个web服务调用
我正在使用jQuery2.2.0编写我的第一个JavaScript Chrome扩展,它基本上采用当前URL并轮询几个不同的web服务,以查看它们是否有URL记录。如果它存在,我会在DOM中添加一个文本链接。以下是一个简化的工作版本:Javascript 来自chrome扩展的多个web服务调用,javascript,jquery,google-chrome-extension,Javascript,Jquery,Google Chrome Extension,我正在使用jQuery2.2.0编写我的第一个JavaScript Chrome扩展,它基本上采用当前URL并轮询几个不同的web服务,以查看它们是否有URL记录。如果它存在,我会在DOM中添加一个文本链接。以下是一个简化的工作版本: // Does the provided URL exist? function url_exists(url) { var h = new XMLHttpRequest(); h.open('HEAD', url, false); h.s
// Does the provided URL exist?
function url_exists(url) {
var h = new XMLHttpRequest();
h.open('HEAD', url, false);
h.send();
return h.status!=404;
}
// Display a link to the database record URL in the DOM
function display_database_link(url) {
$('body').prepend('<a href="' + url + '">Link</a>');
}
// Get the current URL
var url = window.location.href;
var database_number = 0;
// See if this URL exists in one of our databases via the API
// Does the URL exist in database 1?
if (url_exists("https://api.database1.com/urls/" + url)) {
database_number = 1;
}
// Does the URL exist in database 2?
else if (url_exists("https://api.database2.com/urls/" + url)) {
database_number = 2;
}
if (database_number > 0) {
display_database_link("https://api.database" + database_number + ".com/urls/" + url))
}
//提供的URL是否存在?
函数url_存在(url){
var h=新的XMLHttpRequest();
h、 打开('HEAD',url,false);
h、 send();
返回h.status!=404;
}
//在DOM中显示指向数据库记录URL的链接
功能显示\数据库\链接(url){
$('body')。前缀(“”);
}
//获取当前URL
var url=window.location.href;
var数据库_编号=0;
//通过API查看此URL是否存在于我们的一个数据库中
//数据库1中是否存在URL?
如果(url_)存在(“https://api.database1.com/urls/“+url”){
数据库号=1;
}
//数据库2中是否存在URL?
否则,如果(url_)存在(“https://api.database2.com/urls/“+url”){
数据库号=2;
}
如果(数据库编号>0){
显示数据库链接(“https://api.database“+database_number+”.com/url/“+url))
}
我所拥有的一切都有效,但我想知道:
h.open('HEAD',url,false)
第三个参数(false
)定义请求是异步的还是同步的。。。。应将其设置为true:数据库\u number
是否大于0es2015有两个很棒的功能,可以让这一切变得轻松愉快:和。你将不得不做一些调整,但类似的事情应该工作
// Array of API endpoints to to make requests to
let url = window.location.href;
let database_urls = ["https://api.database1.com/urls/", "https://api.database2.com/urls/"];
// Promise.all will take an array of promises and perform all of them, and `then` process all results at the end
Promise.all(database_urls.map(database_url =>
// Make an HTTP request to the endpoint, and `then` get the status code from the response
fetch(database_url + url).then(response => response.status)
// Once `all` promises are resolved, `then` iterate over the resulting statuses
)).then(statuses => {
// Reduce `statuses` to a count of how many are not 404s
let existCount = statuses.reduce((prev, curr) => {return curr == 404 ? prev : prev + 1}, 0);
// Call method to display link if existsCount is > 0
});
如果您无论如何都在使用Jquery,为什么要
XMLHttpRequest
?只需使用$.ajax
和回调。