使用php和jquery将Curl转换为Ajax

时间:2017-07-20 06:27:07

标签: php jquery ajax curl

我只想问......我怎么能转换这段代码:

$url='https://www.zopim.com/api/v2/agents';
$username="boom";
$password="baam";
    // chat user
        $ch1 = curl_init();
        curl_setopt($ch1, CURLOPT_URL, $url);
        curl_setopt($ch1, CURLOPT_USERPWD, "$username:$password");
        curl_setopt($ch1, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
        curl_setopt($ch1, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch1, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch1, CURLOPT_RETURNTRANSFER, true);
        $output1 = curl_exec($ch1);
        $info1 = curl_getinfo($ch1);
        curl_close($ch1);
        $userinfo = json_decode($output1);

到ajax ...我想自动调用json数据...希望你能帮助我...感谢..

1 个答案:

答案 0 :(得分:1)

您可以使用$ .ajax或$ .post来实现此目的。以下是一个例子

PHP脚本中的

<?php
$url='https://www.zopim.com/api/v2/agents';
$username="boom";
$password="baam";
?>

在javacript

<script type="text/javascript">
    // Using the core $.ajax() method
    $.ajax({

        // The URL for the request
        url: "<?php echo $url; ?>",

        // The data to send (will be converted to a query string)
        data: {
            username: "<?php echo $username; ?>",
            password: "<?php echo $password; ?>"
        },

        // Whether this is a POST or GET request
        type: "POST",

        // The type of data we expect back
        dataType : "json",
    })
      // Code to run if the request succeeds (is done);
      // The response is passed to the function
      .done(function( json ) {
         //Hurray!! here is your json data
         console.log(json.id);
         console.log(json.title);

      })
      // Code to run if the request fails; the raw request and
      // status codes are passed to the function
      .fail(function( xhr, status, errorThrown ) {
        alert( "Sorry, there was a problem!" );
        console.log( "Error: " + errorThrown );
        console.log( "Status: " + status );
        console.dir( xhr );
      })
      // Code to run regardless of success or failure;
      .always(function( xhr, status ) {
        alert( "The request is complete!" );
      });
</script>