我正在尝试使用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){...});
答案 0 :(得分:2)
如果您使用$.ajax()
代替($.get()
是简写),您可以use the username
and password
parameters (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 FAQs建议您可能这样做:
<?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;
$.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代码中,因此在您查看页面来源时不可见。
答案 1 :(得分:2)
使用-d
选项的cURL请求会将请求作为POST
个请求发送(除非您为G
请求指定GET
修饰符),因此您需要使用该格式。您还需要使用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 ");
}
);