从curl到jQuery的$ .ajax()函数 [英] From curl to jQuery’s $.ajax() Function

查看:172
本文介绍了从curl到jQuery的$ .ajax()函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于平台的限制,我正在尝试将卷曲代码从称为TextRazor的API转换为jquery的AJAX.我尝试了社区中类似问题的许多解决方案,但似乎无法(通过警报对话框)获取任何数据.如果重要的话 从调用该API的文档中看起来像这样:

I'm trying to convert the curl code from an API called TextRazor to jquery's AJAX because of a platform limitations. I have tried many solutions from similar questions by the community but can't seem to get any data back (through the alert dialog). If it matters from the documentation calling the API looks like this:

curl -X POST \
-H "x-textrazor-key: YOUR_API_KEY" \
-d "extractors=entities,entailments" \
-d "text=Spain's stricken Bankia expects to sell off..." \
https://api.textrazor.com/

我当前的AJAX代码如下:

My current AJAX code looks like this:

$.ajax({
url: "https://api.textrazor.com/",
type: "POST",
dataType: 'json',
data: { 
   x-textrazor-key: "YOUR_API_KEY",
   extractors: "entities,entailments",
   text:"Spain's stricken Bankia expects to sell..." 
},
success:function(data) {
    alert(JSON.stringify(data));
},error: function(xhr) {
    alert("<some error>");
    console.error(xhr.responseText);
}});

如果有帮助,以下是jsfiddle的链接: jsfiddle.net

here is the link to jsfiddle if it helps: jsfiddle.net

感谢您的支持!

推荐答案

这看起来很接近我,但是您将标头放入了POST正文中.我认为应该在下面. (请注意,您还需要在'x-textrazor-key'周围加上引号,否则其中的破折号将被解释为减法.)

This looks close to me, but you put the header into the POST body. I think it should be the below. (Note that you also need quotes around 'x-textrazor-key', since the dashes in it will otherwise be interpreted as subtraction.)

$.ajax({
    url: "https://api.textrazor.com/",
    type: "POST",
    dataType: 'json',
    headers: {
       'x-textrazor-key': "YOUR_API_KEY"
    },
    data: { 
        extractors: "entities,entailments",
        text: "Spain's stricken Bankia expects to sell..." 
    },
    success: function (data) {
        alert(JSON.stringify(data));
    },
    error: function (xhr) {
        alert("<some error>");
        console.error(xhr.responseText);
    }
});

这里当然可能还有其他问题. (例如,API可能不支持跨域请求.)您需要查看浏览器开发人员工具中的网络"标签,以查看实际发生的情况.

There could of course be other issues here. (E.g. perhaps the API doesn't support cross-origin requests.) You'll want to take a look at the network tab in your browser's developer tools to see what actually happens.

这篇关于从curl到jQuery的$ .ajax()函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆