javascript - 在 javascript 中执行 curl 请求?

标签 javascript jquery curl

是否可以在 jQuery 或 javascript 中发送 curl 请求?

是这样的:

curl \
-H 'Authorization: Bearer 6Q************' \
'https://api.wit.ai/message?v=20140826&q='

因此,在 PHP 中提交表单时,如下所示:

$header = array('Authorization: Bearer 6Q************');
$ch = curl_init("https://api.wit.ai/message?q=".urlEncode($_GET['input']));
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$response = curl_exec($ch);
curl_close($ch);

我想做的是执行这个 curl 请求,它返回 json,然后我计划用 jQuery 的 $.get() 函数解析它。

最佳答案

curl 是一个 command in linux (和一个 library in php )。 Curl 通常会发出 HTTP 请求。

您真正想要做的是从 javascript 发出 HTTP(或 XHR)请求。

使用这个词汇你会找到一堆例子,对于初学者来说: Sending authorization headers with jquery and ajax

本质上,您需要调用 $.ajax 并为 header 等设置一些选项。

$.ajax({
        url: 'https://api.wit.ai/message?v=20140826&q=',
        beforeSend: function(xhr) {
             xhr.setRequestHeader("Authorization", "Bearer 6QXNMEMFHNY4FJ5ELNFMP5KRW52WFXN5")
        }, success: function(data){
            alert(data);
            //process the JSON data etc
        }
})

关于javascript - 在 javascript 中执行 curl 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25515936/

相关文章:

javascript - react 创建通用输入组件

javascript - 如何在 'lodash' 函数(debounce)回调函数内部传递参数?

javascript - 将元素中的 CSS 与页面的其余部分隔离

jquery - Bootstrap 3 和 Masonry : Setting four colums

javascript - 如何结合 .load 向 div 添加缓动

jquery - Chrome 和 Safari 上的 jCarousel 文本换行问题

c - 使用 cURL 的段错误

javascript - 无法将我的纬度或经度附加到 html 文档?

linux - 如何使用 cURL 测试并等待 HTTP 服务?

c - 在c中使用libcurl每n秒发送一次请求