is it possible to set custom headers on js <script> requests?

纵饮孤独 提交于 2020-01-03 15:27:25

问题


Is something like this possible?

<script src="http://myserver.com/some.js" my-custom-header="foo"></script>

Update (a bit more detail):

I've been asked if there was a way to communicate some parameters to the server as part of the script request using headers instead of GET params. I said, "no," but thought I'd double check.


回答1:


Short answer: no. By default a script tag will just retrieve the resource specified in the src attribute.

However, if you use an AJAX request to retrieve the script (and add it later/execute it), you can use the setRequestHeader function of the XMLHttpRequest object (see http://www.developertutorials.com/learn-ajax/custom-http-headers-2643.php).

You could also use more complex methods, such as using mod_rewrite to rewrite paths, and include the parameters in the url. The best solution depends on what you want to do, and how much control you have over the server.




回答2:


No. You'll need to set the headers on the server that's serving up the JS file.

EDIT: I misinterpreted what you meant, it turns out you wanted to set a request header, not a response header. This is still not possible (from HTML) as far as I know.



来源:https://stackoverflow.com/questions/4866722/is-it-possible-to-set-custom-headers-on-js-script-requests

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!