dsfjk44656 2017-02-24 07:28
浏览 726
已采纳

如何在Ajax中调用curl命令

Here is my curl command is there anyway to execute this command using ajax

curl -X POST -u "CONVERSATION_USERNAME":"CONVERSATION_PASSWORD" -H "Content-Type:application/json" -d "{\"input\": {\"text\":\" \"}}" "https://gateway.watsonplatform.net/conversation/api/v1/workspaces/CONVERSATION_ID/message?version=2016-07-11"
  • 写回答

3条回答 默认 最新

  • douju5062 2017-02-28 09:55
    关注

    Create a PHP file.here file name is chat.php

    <?php
    if(isset($_POST['conversation'])) {
    $data = array("input"=>array("text"=>$_POST["conversation"]));
    $url = "https://gateway.watsonplatform.net/conversation/api/v1/workspaces/a9379972-d820-4cdf-b1cb-ad0af898a534/message?version=2016-07-11";
    $ch = curl_init($url);
    curl_setopt_array($ch, array(
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_USERPWD => "username:password",
        CURLOPT_HTTPHEADER => array("Content-Type:application/json"),
        CURLOPT_POSTFIELDS => json_encode($data),
    ));
    $response = curl_exec($ch);
    curl_close($ch);
    print_r(json_decode($response));
     }
     ?>
    

    and call this by using Ajax

    var xhr = new XMLHttpRequest();
    //xhr.open('get', 'chat.php');
    xhr.open("GET", "chat.php?data=" + data to be pass, false);
    // Track the state changes of the request.
    xhr.onreadystatechange = function () {
    var DONE = 4; // readyState 4 means the request is done.
    var OK = 200; // status 200 is a successful return.
    if (xhr.readyState === DONE) {
        if (xhr.status === OK) {
            //alert(xhr.responseText); 
            talking = true;
            botMessage=xhr.responseText;// 'This is the returned text.'
        } else {
            // console.log('Error: ' + xhr.status); // An error occurred during the request.
            alert ('Error: ' + xhr.status);
        }
    }
    };
    
     // Send the request to send-ajax-data.php
     xhr.send();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog