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 关于博途V17进行仿真时无法建立连接问题
  • ¥15 请问下这个红框里面是什么文档或者记事本编辑器
  • ¥15 机器学习教材中的例题询问
  • ¥15 求.net core 几款免费的pdf编辑器
  • ¥15 为什么安装HCL 和virtualbox之后没有找到VirtualBoxHost-OnlyNetWork?
  • ¥15 C# P/Invoke的效率问题
  • ¥20 thinkphp适配人大金仓问题
  • ¥20 Oracle替换.dbf文件后无法连接,如何解决?(相关搜索:数据库|死循环)
  • ¥15 数据库数据成问号了,前台查询正常,数据库查询是?号
  • ¥15 算法使用了tf-idf,用手肘图确定k值确定不了,第四轮廓系数又太小才有0.006088746097507285,如何解决?(相关搜索:数据处理)