如何使用jquery调用jsonp?

时间:2016-04-17 08:06:04

标签: javascript jquery ajax

我有这个api http://api.program-o.com/v2/chatbot/?bot_id=6&say=what%20is%20your%20name&convo_id=exampleusage_1231232&format=xml我使用浏览器调用然后我得到了正确的回复。但是当我使用jquery ajax调用时,我收到了错误

*Refused to execute script from 'http://api.program-o.com/v2/chatbot/?bot_id=6&say=what%20is%20your%20name&c…ormat=xml&callback=?%20&callback=jQuery172005527849208121283_1460880216789' because its MIME type ('text/xml') is not executable, and strict MIME type checking is enabled.*

代码如下

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>JQuery (cross-domain) JSONP Twitter example</title>
        <script type="text/javascript"src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
        <script>
            $.ajax({
    url: "http://api.program-o.com/v2/chatbot/?bot_id=6&say=what%20is%20your%20name&convo_id=exampleusage_1231232&format=xml&callback=? ",
    type: "GET",
    dataType: 'jsonp',
    cache: true,
    success: function (data, status, error) {
      console.log('success', data);
    },
    error: function (data, status, error) {
      console.log('error', data, status, error);
    }
});
        </script>
    </head>
    <body>
        <ul id="gists"></ul>
    </body>
</html>

有人可以告诉我为什么我做错了吗?

3 个答案:

答案 0 :(得分:0)

您的回复是一个XML文件。您应该将format查询更改为json

以下是JSON中的回复:

{"convo_id":"exampleusage_1231232","usersay":"WHAT IS YOUR NAME","botsay":"My name is Program-O."}

答案 1 :(得分:0)

问题出在这里

$.ajax({
    url: "http://api.program-o.com/v2/chatbot/?bot_id=6&say=what%20is%20your%20name&convo_id=exampleusage_1231232&format=xml&callback=? ",
    type: "GET",
    dataType: 'jsonp',

您正在申请XML

http://api.program-o.com/v2/chatbot/?bot_id=6&say=what%20is%20your%20name&convo_id=exampleusage_1231232&format=xml

如果您将XML替换为JSON,它应该有效。

http://api.program-o.com/v2/chatbot/?bot_id=6&say=what%20is%20your%20name& convo_id=exampleusage_1231232&format=json

答案 2 :(得分:0)

当你试图直接打电话给 在浏览器中http://api.program-o.com/v2/chatbot/?bot_id=6&say=what%20is%20your%20name&convo_id=exampleusage_1231232&format=json,您会注意到返回标头为Content-Type:text/plain; charset=utf-8X-Content-Type-Options:nosniff。它告诉Chrome有严格的MIME类型检查。您是否可以尝试将服务器输出内容类型更改为application/javascript或删除X-Content-Type-Options:nosniff