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 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用