javascript - 在 JSONP 请求中设置响应内容类型 header ?

标签 javascript jquery ajax utf-8 jsonp

我有一个用例,我在其中发出跨域 JSONP 请求。

$.ajax({
  url: "http://anyorigin.com/get/?url=<any_website_url>&callback=?'",
  dataType: 'jsonp',
  success: function(data) {
    console.log(data);
}});

它工作正常,但我注意到中文网站的数据出现乱码。我对此进行了调试,发现响应头始终设置为:

Response Header: Content-Type:text/javascript; charset=ISO-8859-1

现在这个字符集 ISO-8859-1 造成了问题。它应该是UTF-8。我基本上想始终将此字符集覆盖为 UTF-8。我知道我可以使用 ajax 来做到这一点。我尝试使用以下代码 -

$.ajax({
  url: "http://anyorigin.com/get/?url=www.google.com&callback=?'",
  dataType: 'jsonp',
  beforeSend: function(xhr) {
    console.log(xhr);
    xhr.overrideMimeType("text/javascript; charset=utf-8");
  },
  success: function(data) {
    console.log(data);
}});

但这并没有解决问题。我猜因为 JSONP 请求不使用 XHR 对象,所以这行不通。

谁能告诉我如何实现这个目标,或者它是否可以实现? TIA。

最佳答案

jsonp 请求本质上是一个使用 <script> 包含的外部 javascript 文件标签。幸运的是 <script> -元素有一个 charset您可以设置的属性 UTF-8 .因此,这看起来像

<script 
  src="http://anyorigin.com/get/?url=<any_website_url>&callback=myCallbackFunction"
  charset="UTF-8"
></script>

哪里myCallbackFunction之前已定义并将使用请求的数据调用。所以你得到的是

<script>
  window.myCallbackFunction = function(data){
  }
  // Dynamically insert the previously describe <script> tag here.
</script>

事实证明,这也可以直接在jQuery.ajax上实现。函数通过设置 scriptCharset 来选择属性(property)。

Only applies when the "script" transport is used (e.g., cross-domain requests with "jsonp" or "script" dataType and "GET" type). Sets the charset attribute on the script tag used in the request. Used when the character set on the local page is not the same as the one on the remote script.

关于javascript - 在 JSONP 请求中设置响应内容类型 header ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30117593/

相关文章:

ajax - 成功,错误事件不适用于 ajax

javascript - 带有 Meteor 的 Malihu jQuery 自定义滚动条不显示

javascript - jQuery 数字计数器不接受逗号

JQuery MagicLine 导航到下拉菜单

jquery - 本地滚动 anchor 链接相对于另一个页面的偏移量

jquery - 使用 jQuery 模拟 AJAXy 单击以选择菜单

javascript - Lodash基于外部数组对集合进行排序

javascript - 我可以让这个字符串成为多行吗?

javascript - 使用 axios 时获取字节

javascript - 将简单的 Perl 脚本翻译成 Python 以向客户端发送响应?