可以用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()函数解析它。
发布于 2014-08-27 06:11:23
curl是一个command in linux (也是一个library in php)。Curl通常会发出HTTP请求。
您真正想做的是从javascript发出一个HTTP (或XHR)请求。
使用这个单词,你会找到一堆入门的例子:Sending authorization headers with jquery and ajax
从本质上讲,你需要调用带有一些头部选项的$.ajax,等等。
$.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
}
})发布于 2019-08-09 06:18:40
您可以使用JavaScripts Fetch API (在浏览器中提供)发出网络请求。
如果使用node,则需要安装node-fetch包。
const url = "https://api.wit.ai/message?v=20140826&q=";
const options = {
headers: {
Authorization: "Bearer 6Q************"
}
};
fetch(url, options)
.then( res => res.json() )
.then( data => console.log(data) );发布于 2017-11-03 05:00:20
可以,使用getJSONP。这是进行跨域/服务器异步调用的唯一方法。(*或者在不久的将来)。就像这样
$.getJSON('your-api-url/validate.php?'+$(this).serialize+'callback=?', function(data){
if(data)console.log(data);
});回调参数会由浏览器自动填写,不用担心。
在服务器端('validate.php'),你会看到类似这样的东西
<?php
if(isset($_GET))
{
//if condition is met
echo $_GET['callback'] . '(' . "{'message' : 'success', 'userID':'69', 'serial' : 'XYZ99UAUGDVD&orwhatever'}". ')';
}
else echo json_encode(array('error'=>'failed'));
?>https://stackoverflow.com/questions/25515936
复制相似问题