如何将这个curl请求转换为jquery请求
How would I turn this curl request into a jquery request?
我试图使用API,但它们的示例是curl,而不是javascript,这是我最熟悉的。以下是他们的例子:
$ curl http://visearch.visenze.com/uploadsearch '
-d im_url=http://example.com/example-0.jpg '
-d box=0,0,20,20 '
-u access_key:secret_key
这是我对等效jquery请求的尝试,但它不起作用。
$.get("http://visearch.visenze.com/uploadsearch/im_url=http://example.com/example-0.jpg/box=0,0,20,20/u access :secret_key", function(data){...});
-d
选项的cURL请求将请求作为POST
请求发送(除非为GET
请求指定了G
修饰符),因此需要使用该格式。您还需要在beforeSend
方法中设置标题:
$.ajax(
'http://visearch.visenze.com/uploadsearch',
type: 'post',
data: {
im_url: 'http://example.com/example-0.jpg',
box: '0,0,20,20'
},
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", "Basic ");
}
);
如果使用$.ajax()
($.get()
是其简写),则可以使用username
和password
参数(jQuery 1.7.2+)进行基本身份验证。如果需要该请求方法,则需要传递一个数据对象并指定POST。
$.ajax(
url: 'http://visearch.visenze.com/uploadsearch',
data: {
im_url: 'http://example.com/example-0.jpg',
box: '0,0,20,20',
},
username: 'access_key',
password: 'secret_key',
type: 'POST',
success: function(data) {
// ... your callback
}
);
既然您已经在这个问题中标记了PHP,我将展示一个示例,说明您可能希望如何像Visenze API常见问题解答所建议的那样,将访问密钥等隐藏在后端包装器中:
1.创建一个PHP文件
<?php
$accessKey = 'access_key';
$secretKey = 'secret_key';
if (isset($_POST['im_url'], $_POST['box'])) {
// Initialize the cURL request to ViSenze
$ch = curl_init('http://visearch.visenze.com/uploadsearch');
// We want to RETURN the result not output it
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set up the basic authentication settings
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, "$accessKey:$secretKey");
// Define the post fields
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, [
'im_url' => $_POST['im_url'],
'box' => $_POST['box']
]);
// Do the request
$result = curl_exec();
curl_close($ch);
// Output the results
echo $result;
exit;
}
echo 'Nothing posted to this script.';
exit;
2.使用jQuery调用该文件
$.post(
'http://visearch.visenze.com/uploadsearch',
{
im_url: 'http://example.com/example-0.jpg',
box: '0,0,20,20',
},
function(data) {
// ... your callback
}
);
通过这种方式,您的API凭据存储在PHP代码中,因此在查看页面源代码时不可见。
相关文章:
- 将GET请求(HTML字符串)转换为完整的DOM对象
- 将curl转换为节点请求
- 如何在JavaScript中将JSP请求属性转换为字符串并将其分配给对象
- 如何将日期选择器日期转换为JSON对象以用于AJAX请求
- 将curl转换为ajax请求
- 将php-soap请求转换为javascript
- 如何在Windows 8 JavaScript(Metro)中将twitter oAuth请求令牌转换为访问令牌
- 如何将 xhr 请求转换为角度$http请求
- 在 $.ajaxSetup 转换器中获取 ajax 请求 URL,以便进行日志记录
- RxJs - 将 Flickr 请求转换为照片流
- 是否有将 WebSocket 请求转换为服务器上的 HTTP 请求的标准
- 将 API 请求转换为要在站点中使用的文本
- 如何将这个curl请求转换为jquery请求
- 将CURL请求转换为云代码中的Parse.com HttpWebRequest
- 将AJAX请求转换为jQuery
- 将JSON HTTP POST请求转换为Java对象时出错
- Angularjs延迟加载时请求转换的多个指令
- 如何将dropbox API v2 POST HTTP请求转换为jQuery$.ajax
- 如何传递AngularUI谷歌地图对象到工厂或请求转换
- 如何将我的get请求转换为post请求