Javascript 如何将这个curl请求转换为jquery请求?

Javascript 如何将这个curl请求转换为jquery请求?,javascript,php,jquery,curl,Javascript,Php,Jquery,Curl,我试图使用一个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://visea

我试图使用一个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){...}); 
如果改为使用哪一个$.get是缩写,则可以将其用于基本身份验证。如果需要该请求方法,则需要传递一个数据对象并指定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,我将展示一个示例,说明您可能希望如何将访问密钥等隐藏在后端包装器中,正如建议的那样:

1.创建一个PHP文件 通过这种方式,API凭据存储在PHP代码中,因此在查看页面源代码时不可见。

带有-d选项的cURL请求将请求作为POST请求发送,除非您为GET请求指定了G修饰符,因此需要使用该格式。您还需要在beforeSend方法中设置标头:


-d在一篇文章中作为数据发送,所以至少,您需要一个$。postit不起作用不是一个问题陈述,是吗?您应该确保这不是一个问题。如果您试图在其域之外访问API,这很可能是一个问题。我想,如果他们一开始没有指定JavaScript作为替代方案,这将是一个问题。我有点担心,您正在尝试使用一个api,该api在jQuery中具有访问权限和秘密参数,这意味着它在网站上,这意味着您将泄露这些值。。。我希望这个网站是短暂的,不能从公共互联网上获得!话虽如此,我不太清楚在这个问题上所有的否决票是怎么回事。谢谢,@RobbieAverill。
<?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
    }
);
$.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 ");
  }
);