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

Setting response content type header in JSONP request?

我有一个发出跨域 JSONP 请求的用例。

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

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

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 object,这将不起作用。

任何人都可以告诉我如何实现这一点,或者它是否可以实现? 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>

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

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.

你说得对,JSONP 没有使用 XHR 对象,它使用了 script 标签。

但是,这可以通过使用 scriptCharset 选项的 jQuery JSONP 包装器来完成。

摘自jQuery.ajax docs

scriptCharset

Type: String

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.

要让 jQuery 将 UTF-8 charset 属性添加到 JSONP script 标签,您只需将 scriptCharset: 'UTF-8' 添加到您的 AJAX 设置对象。

示例代码:

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