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

如何在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 在若依框架下实现人脸识别
  • ¥15 网络科学导论,网络控制
  • ¥100 安卓tv程序连接SQLSERVER2008问题
  • ¥15 利用Sentinel-2和Landsat8做一个水库的长时序NDVI的对比,为什么Snetinel-2计算的结果最小值特别小,而Lansat8就很平均
  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同