【发布时间】:2018-03-02 06:20:00
【问题描述】:
我正在使用 ajax 连接到 Watson Language Translator API。基本身份验证可以通过,因此它可以从 google chrome 控制台上的 URL 输出检查 API 的输出。但是,ajax 无法读取输出结果。在控制台中,也会出现以下错误。
“拒绝执行来自'https://gateway.watsonplatform.net/language-translator/api/v2/translate?callback=jQuery3210879483874866891_1519969671034&text=Hello%20Wordl&source=en&target=es&_=1519969671035'的脚本;因为它的MIME类型('text/plain')不可执行,并且启用了严格的MIME类型检查。”
原因是 MIME 类型,我不知道如何更改它。如果您知道解决方案,请告诉我。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>client</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$("#btn").click(function(){
$.ajax({
url: 'https://gateway.watsonplatform.net/language-translator/api/v2/translate',
type:'POST',
data : {'text': 'Hello Wordl', 'source': 'en', 'target': 'es'},
dataType: 'jsonp',
jsonp: 'callback',
headers: { Authorization: 'Basic XXXXXXXXXXX:XXXXXXX'}
})
.done(function(data){
console.dir(data);
})
.fail(function(data){
console.dir(data);
});
});
});
</script>
</head>
<body>
<button id="btn">TEST</button>
</body>
</html>
我访问了控制台消息“拒绝从.....执行脚本”的 URL。翻译的“Hello World”只有“Hola Mundo”。该页面的源代码如下。另外,下载页面后,是一个名为“translate.txt”的文本文件
<html>
<head>
<style id="style-1-cropbar-clipper">/* Copyright 2014 Evernote Corporation. All rights reserved. */
.en-markup-crop-options {
top: 18px !important;
left: 50% !important;
margin-left: -100px !important;
width: 200px !important;
border: 2px rgba(255,255,255,.38) solid !important;
border-radius: 4px !important;
}
.en-markup-crop-options div div:first-of-type {
margin-left: 0px !important;
}
</style></head>
<body>
<pre style="word-wrap: break-word; white-space: pre-wrap;">Hola Mundo</pre>
</body>
</html>
【问题讨论】:
-
你能告诉我们一些数据吗,ajax调用会获取吗?
-
代码中的问题是,您传递了
dataType: 'jsonp',,但API 返回的是纯文本响应(text/plain)。 -
感谢您的回复。我访问了控制台消息“拒绝从.....执行脚本”的 URL。翻译的“Hello World”只有“Hola Mundo”。源代码在此问题的更新部分中进行了描述。另外,下载页面后,是一个名为“translate.txt”的文本文件。