javascript 如何为网页上的链接设置接受标题?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20361216/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I set the Accept Header for a link on a web page?
提问by Frew Schmidt
This is mostly an ivory tower question, since I can easily just make a new URL endpoint. But basically, I'd like to be able to serve up CSV when the user has the Accept header configured to include text/csv. That's trivial on the server side, but on the client side I don't know how to set the Accept header unless I'm using XHR or some other "non-browser" client. Is there a way in HTML to set the Accept header in a link or in JS to set the Accept header when using window.location?
这主要是一个象牙塔问题,因为我可以轻松地创建一个新的 URL 端点。但基本上,当用户将接受标头配置为包含文本/csv 时,我希望能够提供 CSV。这在服务器端是微不足道的,但在客户端我不知道如何设置 Accept 标头,除非我使用 XHR 或其他一些“非浏览器”客户端。有没有办法在 HTML 中设置链接中的 Accept 标头或在 JS 中使用 window.location 时设置 Accept 标头?
采纳答案by Frew Schmidt
I figure I might as well put this here for the next thousand people looking at the post. You cannot do it.
我想我不妨把它放在这里,让接下来的一千个人看这篇文章。你做不到。
回答by Rob M.
Update:
更新:
I will leave my original answer below for posterity, but I now see that I didn't really answer the question. There isn't a way to do this "natively", the best approach I can think of would be to use a data uri (http://en.wikipedia.org/wiki/Data_URI_scheme) and have AJAX do the work for you:
我将在下面留下我的原始答案以供后代使用,但现在我发现我并没有真正回答这个问题。没有办法“本地”执行此操作,我能想到的最佳方法是使用数据 uri ( http://en.wikipedia.org/wiki/Data_URI_scheme) 并让 AJAX 为您完成工作:
// aware that you didn't mention jQuery, but you can do this with or without
var download = function(){
var mime = this.getAttribute('data-mime-type');
$.ajax({
accepts: mime,
success: function(data){
var uri = 'data:'+mime+';charset=UTF-8,' + encodeURIComponent(data);
window.location = uri;
}
})
return false;
}
With the same idea used in the example below:
使用以下示例中使用的相同想法:
<a href="/some-csv-endpoint" data-mime-type="text/csv">Download CSV</a>
<a href="/some-csv-endpoint" data-mime-type="text/csv">Download CSV</a>
document.querySelectorAll('a[data-mime-type]').onclick = download;
document.querySelectorAll('a[data-mime-type]').onclick = download;
Original Answer
原答案
There is no built-in way to force an 'Accept' header on a link (via HTML or Javascript). I think you could pull this off fairly easily using a very small amount of server & client-side code though. Should be easy in any language, my example is PHP:
没有内置的方法来强制链接上的“接受”标头(通过 HTML 或 Javascript)。我认为您可以使用非常少量的服务器和客户端代码轻松实现这一点。用任何语言都应该很容易,我的例子是 PHP:
function get_accepted_headers() {
$headers = apache_request_headers();
if(array_key_exists('Accept', $headers)) {
$accepted = explode(',', $headers['Accept']);
return $accepted;
}
return array();
}
Add a data-accept attribute to your download links:
将数据接受属性添加到您的下载链接:
<a href="/some-csv-file.csv" data-accept="text/csv">Download CSV</a>
<a href="/some-csv-file.csv" data-accept="text/csv">Download CSV</a>
Then attach a click event handler to ensure that the user accepts the specified content type:
然后附加一个点击事件处理程序以确保用户接受指定的内容类型:
// will end up with something like: ["text/html", "application/xhtml+xml", "application/xml;q=0.9", "image/webp", "*/*;q=0.8"]
var user_headers = <?=stripslashes(json_encode(get_accepted_headers()))?>;
var click_header_check = function() {
var accept = this.getAttribute('data-accept');
if(user_headers.indexOf(accept) == -1) {
console.log('User does not explicitly accept content-type: %s', accept);
return false;
}
window.location = this.href;
return;
}
// attach the event listener
document.querySelector('a[data-accept]').onclick = click_header_check;
Not sure if this is what you were looking for, but hope that it helps.
不确定这是否是您要查找的内容,但希望它有所帮助。
回答by Tom
For those still interested, there is a way to do this in pure javascript.
对于那些仍然感兴趣的人,有一种方法可以在纯 javascript 中做到这一点。
The following code uses JQuery (https://jquery.com/) and FileSaver.js (http://purl.eligrey.com/github/FileSaver.js/blob/master/FileSaver.js) though you could write the respective parts yourself:
以下代码使用 JQuery ( https://jquery.com/) 和 FileSaver.js ( http://purl.eligrey.com/github/FileSaver.js/blob/master/FileSaver.js) 尽管您可以编写各自的自己零件:
//in case of non binary data use:
var type = 'text/xml';
var url = 'http://your_url_here/'
$.ajax({accepts:{text:type},
url:url,
processData:false,
dataType:'text',
success:function(data){
saveAs(new Blob([data], {type: type}),'filename.txt');
},
error: function(){
// Handle errors here
}
});