【问题标题】:MySQL select result inside JS functionJS函数内的MySQL选择结果
【发布时间】:2018-04-27 12:51:23
【问题描述】:

我找到了一个简单的 JS 脚本,它可以用作聊天机器人。 在脚本本身中,lastUserMessage 的结果是内联预定义的,如

if (lastUserMessage === 'name') {
   botMessage = 'My name is ' + botName;
}

我想要实现的是,如果 JS 在数据库中搜索 lastUserMessage 并从那里提供 botMessage。 p>

我相信它应该不会那么难,但我不知道该怎么做。

这里是 JS 代码:

nlp = window.nlp_compromise;
var messages = [], //array that hold the record of each string in chat
  lastUserMessage = "", //keeps track of the most recent input string from the user
  botMessage = "", //var keeps track of what the chatbot is going to say
  botName = 'Bot Name', //name of the chatbot
  talking = true; //when false the speach function doesn't work

//edit this function to change what the chatbot says
function chatbotResponse() {
  talking = true;
  botMessage = "Ops... didn't get this"; //the default message

  if (lastUserMessage === 'name') {
    botMessage = 'My name is ' + botName;
  }

}

//this runs each time enter is pressed.
//It controls the overall input and output
function newEntry() {
  //if the message from the user isn't empty then run 
  if (document.getElementById("chatbox").value != "") {
    //pulls the value from the chatbox ands sets it to lastUserMessage
    lastUserMessage = document.getElementById("chatbox").value;
    //sets the chat box to be clear
    document.getElementById("chatbox").value = "";
    //adds the value of the chatbox to the array messages
    messages.push(lastUserMessage);
    //Speech(lastUserMessage);  //says what the user typed outloud
    //sets the variable botMessage in response to lastUserMessage
    chatbotResponse();
    //add the chatbot's name and message to the array messages
    messages.push("<b>" + botName + ":</b> " + botMessage);
    // says the message using the text to speech function written below
    Speech(botMessage);
    //outputs the last few array elements of messages to html
    for (var i = 1; i < 8; i++) {
      if (messages[messages.length - i])
        document.getElementById("chatlog" + i).innerHTML = messages[messages.length - i];
    }
  }
}

//runs the keypress() function when a key is pressed
document.onkeypress = keyPress;
//if the key pressed is 'enter' runs the function newEntry()
function keyPress(e) {
  var x = e || window.event;
  var key = (x.keyCode || x.which);
  if (key == 13 || key == 3) {
    //runs this function when enter is pressed
    newEntry();
  }
  if (key == 38) {
    console.log('hi')
      //document.getElementById("chatbox").value = lastUserMessage;
  }
}

//clears the placeholder text ion the chatbox
//this function is set to run when the users brings focus to the chatbox, by clicking on it
function placeHolder() {
  document.getElementById("chatbox").placeholder = "";
}

这是 HTML 代码

<div id='bodybox'>
  <div id='chatborder'>
    <p id="chatlog2" class="chatlog">&nbsp;</p>
    <p id="chatlog1" class="chatlog">&nbsp;</p>
    <input type="text" name="chat" id="chatbox" placeholder="Hi there! Type here to talk to me." onfocus="placeHolder()">
  </div>

需要做什么?

理想情况下,脚本应采用值“lastUserMessage”和 来自具有 2 列“lastUserMessage”的数据库的“botMessage”和 “botMessage”。

我试图按照下面 Ghost 的评论...但没有用。

    nlp = window.nlp_compromise;
var messages = [], //array that hold the record of each string in chat
  lastUserMessage = "", //keeps track of the most recent input string from the user
  botMessage = "", //var keeps track of what the chatbot is going to say
  botName = 'Bot Name', //name of the chatbot
  talking = true; //when false the speach function doesn't work

//edit this function to change what the chatbot says
function chatbotResponse() {
  talking = true;
  botMessage = "Ops... didn't get this"; //the default message

      $.ajax({                                      
  url: 'db_query.php',         
  data: "lastUserMessag=lastUserMessag", 
  dataType: 'json',                 
  success: function(data)          
  {
    var lastUserMessage_db = data[0]; 
    var botMessage_db= data[1];

if (lastUserMessage === lastUserMessage_db) {
    botMessage = botMessage_db;
  }
  } 
});

}

//this runs each time enter is pressed.
//It controls the overall input and output
function newEntry() {
  //if the message from the user isn't empty then run 
  if (document.getElementById("chatbox").value != "") {
    //pulls the value from the chatbox ands sets it to lastUserMessage
    lastUserMessage = document.getElementById("chatbox").value;
    //sets the chat box to be clear
    document.getElementById("chatbox").value = "";
    //adds the value of the chatbox to the array messages
    messages.push(lastUserMessage);
    //Speech(lastUserMessage);  //says what the user typed outloud
    //sets the variable botMessage in response to lastUserMessage
    chatbotResponse();
    //add the chatbot's name and message to the array messages
    messages.push("<b>" + botName + ":</b> " + botMessage);
    // says the message using the text to speech function written below
    Speech(botMessage);
    //outputs the last few array elements of messages to html
    for (var i = 1; i < 8; i++) {
      if (messages[messages.length - i])
        document.getElementById("chatlog" + i).innerHTML = messages[messages.length - i];
    }
  }
}

//runs the keypress() function when a key is pressed
document.onkeypress = keyPress;
//if the key pressed is 'enter' runs the function newEntry()
function keyPress(e) {
  var x = e || window.event;
  var key = (x.keyCode || x.which);
  if (key == 13 || key == 3) {
    //runs this function when enter is pressed
    newEntry();
  }
  if (key == 38) {
    console.log('hi')
      //document.getElementById("chatbox").value = lastUserMessage;
  }
}

//clears the placeholder text ion the chatbox
//this function is set to run when the users brings focus to the chatbox, by clicking on it
function placeHolder() {
  document.getElementById("chatbox").placeholder = "";
}

在 DB_query.php 我有

$p = $_GET['lastUserMessag']; 
      $query=mysql_query("SELECT lastUserMessag, botMessage FROM `aiml` WHERE lastUserMessag='$p'");
      $array = mysql_fetch_row($query);  
    echo json_encode($array);

【问题讨论】:

  • 这在什么服务器上运行?
  • 我想您使用的是客户端 JS,那么服务器端应用程序是什么样的?客户端 JS 向服务器执行 HTTP 请求,服务器通过一些查询查看数据库。我看不到 JS 在哪里直接发出 MySQL 查询。
  • 它在 Windows 服务器上。 JS 不发出 MySQL 查询....我相信这是我需要发生的事情。
  • 您需要 GET/POST 访问 MySQL 数据库的服务器。否则,您可以使用本地存储,尽管我不确定这是否是您想要的以及是否所有浏览器都支持它。阅读:html5rocks.com/en/tutorials/offline/storage
  • 所以您希望 SO 用户为您编写服务器端代码?您是否尝试过搜索并了解如何实现这一目标?

标签: javascript html mysql


【解决方案1】:

Javascript 在客户的浏览器中运行。 MySQL 在服务器中运行。所以,需要其他东西来连接它们。

我使用 PHP 和 AJAX 作为它们之间的管道。 JS 发出 AJAX 调用。 (注意:“A”代表“异步”。)然后 JS 通过“回调”获取结果。同时,AJAX“调用”的目标是一个PHP程序(或Java或VB或......),它连接到数据库(MySQL)并执行SELECT并构建JSON以返回给JS。

【讨论】:

    【解决方案2】:

    您正在执行的 Javascript 当前在浏览器中运行,但未连接到您可以从中获取数据的任何数据库。

    为此,您必须向后端服务器(假设您有一个)发送一个 POST 或 GET 请求,我认为该请求是使用 NodeJS 用 JS 编写的。

    请注意,您应该绝不向用户授予对所述数据库的访问权限(例如,将数据库连接到您现在正在使用的代码,该代码在浏览器中执行)然后他们就可以用它做任何他们想做的事情。

    如果您想查看NodeJS 以及如何处理请求,我建议您根据您的专业水平查看 W3Schools 上的 ExpressJSthis great MySQL + NodeJS tutorial

    【讨论】:

    • 谢谢,我已经尝试过了...但由于某种原因它不想触发对数据库的请求
    • 如果使用 NodeJS,而不是 AJAX 请求,我建议使用 websocket
    • 为此建议ExpressJS 太过分了。如果您只想访问数据库并将数据返回给客户端,为什么要使用功能齐全的框架?或者任何框架?它可能更容易开始,但在我看来这不是一个好的学习方式。
    【解决方案3】:

    您确认db_query.php 有效吗?

    尝试使用 POSTMAN 或 Broswer 之类的 Chrome 来访问网址。 localhost/db_query.php 或正确的,看看你是否得到了你期望的结果。

    如果你得到了预期的结果,那么你的 JavaScript 有问题。

    $.ajax 是异步的,所以它会被调用并且 javascript 会继续执行。

    我试着解释一下。你打电话给chatbotResponse() 女巫在$.ajax 上调用success 设置数据

    var lastUserMessage_db = data[0]; 
    var botMessage_db= data[1];
    

    但是 $.ajax 是异步的,所以 javascript 将继续执行,所以这个 javascript 代码将在调用成功之前运行

        //add the chatbot's name and message to the array messages
        messages.push("<b>" + botName + ":</b> " + botMessage);
        // says the message using the text to speech function written below
        Speech(botMessage);
        //outputs the last few array elements of messages to html
        for (var i = 1; i < 8; i++) {
          if (messages[messages.length - i])
            document.getElementById("chatlog" + i).innerHTML = messages[messages.length - i];
        }
    

    所以问题是上面的代码会在你从db_query.php得到lastUserMessage之前运行

    解决方案

    简单的解决方案是将 ajax 更改为同步调用 async:false,这不是最佳做法。

    $.ajax({                                      
      url: 'db_query.php?lastUserMessage='+lastUserMessage,         
      type: "GET",
      async: false,               
      success: function(data)          
      {
        var lastUserMessage_db = data[0]; 
        var botMessage_db= data[1];
    
    if (lastUserMessage === lastUserMessage_db) {
        botMessage = botMessage_db;
      }
      } 
    });
    

    更好的方法是利用成功回调

    例子:

    $.ajax({
          url: 'db_query.php?lastUserMessage='+lastUserMessage,         
          type: "GET",
          success: function(data) {
            var lastUserMessage_db = data[0];
            var botMessage_db = data[1];
    
            if (lastUserMessage === lastUserMessage_db) {
              botMessage = botMessage_db;
            }
    
            //add the chatbot's name and message to the array messages
            messages.push("<b>" + botName + ":</b> " + botMessage);
            // says the message using the text to speech function written below
            Speech(botMessage);
            //outputs the last few array elements of messages to html
            for (var i = 1; i < 8; i++) {
              if (messages[messages.length - i])
                document.getElementById("chatlog" + i).innerHTML = messages[messages.length - i];
            }
    
          }
        });
    

    【讨论】:

    • 我已经尝试使用这两个示例,但由于某种原因它不想执行查询。当我尝试执行 db_query.php 时,它确实返回 lastUserMessage 和 botMessage。我在想的一件事是:Ajax 如何理解它应该使用 POST 还是 GET?或 dataType: 'json' 就足够了?在 db_query.php 我使用 $p = $_GET['lastUserMessage'];从 url 中获取值。
    • 修复 ajax 调用检查一下。
    • 请检查您的代码,您可能有一些拼写错误。我建议使用一些开发工具,例如 chromes 来调试您的代码。
    • 我在 lastUserMessag=lastUserMessag 中有一个错字...已修复。尝试了新代码...但仍然无法正常工作。
    • 我注意到的另一件事是,当我尝试提醒 ajax 中的 lastUserMessage_db 或 botMessage_db 时,它只返回第一个字母
    【解决方案4】:

    这就是我在 Stamos 的帮助下实现它的方法

    nlp = window.nlp_compromise;
    
    var messages = [], //array that hold the record of each string in chat
      lastUserMessage = "", //keeps track of the most recent input string from the user
      botMessage = "", //var keeps track of what the chatbot is going to say
      botName = 'Bot Name', //name of the chatbot
      talking = true; //when false the speach function doesn't work
    //
    
    //****************************************************************
    //edit this function to change what the chatbot says
    function chatbotResponse() {
      talking = true;
      botMessage = "Sorry, Didnt get that"; //the default message
    
      $.ajax({
        url: "appi.php?lastUserMessage=" + lastUserMessage,
        type: "GET",
        async: false,
        success: function(data) {
    
          var obj = JSON.parse(data);
    
          if (lastUserMessage === obj.lastUserMessage) {
            botMessage = obj.botMessage;
          }
        }
      });
    
    }
    
    //****************************************************************
    
    //this runs each time enter is pressed.
    //It controls the overall input and output
    function newEntry() {
      //if the message from the user isn't empty then run 
      if (document.getElementById("chatbox").value != "") {
        //pulls the value from the chatbox ands sets it to lastUserMessage
        lastUserMessage = document.getElementById("chatbox").value;
        //sets the chat box to be clear
        document.getElementById("chatbox").value = "";
        //adds the value of the chatbox to the array messages
        messages.push(lastUserMessage);
        //Speech(lastUserMessage);  //says what the user typed outloud
        //sets the variable botMessage in response to lastUserMessage
        chatbotResponse();
        //add the chatbot's name and message to the array messages
        messages.push("<b>" + botName + ":</b> " + botMessage);
        // says the message using the text to speech function written below
        Speech(botMessage);
        //outputs the last few array elements of messages to html
        for (var i = 1; i < 8; i++) {
          if (messages[messages.length - i])
            document.getElementById("chatlog" + i).innerHTML = messages[messages.length - i];
        }
      }
    }
    
    //text to Speech
    //https://developers.google.com/web/updates/2014/01/Web-apps-that-talk-Introduction-to-the-Speech-Synthesis-API
    function Speech(say) {
      //if ('speechSynthesis' in window && talking) {
      //  var utterance = new SpeechSynthesisUtterance(say);
      //msg.voice = voices[10]; // Note: some voices don't support altering params
      //msg.voiceURI = 'native';
      //utterance.volume = 1; // 0 to 1
      //utterance.rate = 0.1; // 0.1 to 10
      //utterance.pitch = 1; //0 to 2
      //utterance.text = 'Hello World';
      //utterance.lang = 'en-US';
      // speechSynthesis.speak(utterance);
      // }
    }
    
    //runs the keypress() function when a key is pressed
    document.onkeypress = keyPress;
    //if the key pressed is 'enter' runs the function newEntry()
    function keyPress(e) {
      var x = e || window.event;
      var key = (x.keyCode || x.which);
      if (key == 13 || key == 3) {
        //runs this function when enter is pressed
        newEntry();
      }
      if (key == 38) {
        console.log('hi')
        //document.getElementById("chatbox").value = lastUserMessage;
      }
    }
    
    //clears the placeholder text ion the chatbox
    //this function is set to run when the users brings focus to the chatbox, by clicking on it
    function placeHolder() {
      document.getElementById("chatbox").placeholder = "";
    }
    body {
      font: 15px arial, sans-serif;
      background-color: #fff;
      padding-top: 15px;
      padding-bottom: 15px;
    }
    
    #bodybox {
      margin: auto;
      max-width: 550px;
      font: 15px arial, sans-serif;
      background-color: lightgrey;
      border-style: solid;
      border-width: 1px;
      padding-top: 20px;
      padding-bottom: 25px;
      padding-right: 25px;
      padding-left: 25px;
      box-shadow: 5px 5px 5px grey;
      border-radius: 15px;
    }
    
    #chatborder {
      border-style: solid;
      background-color: #f6f9f6;
      border-width: 3px;
      margin-top: 20px;
      margin-bottom: 20px;
      margin-left: 20px;
      margin-right: 20px;
      padding-top: 10px;
      padding-bottom: 15px;
      padding-right: 20px;
      padding-left: 15px;
      border-radius: 15px;
    }
    
    .chatlog {
      font: 15px arial, sans-serif;
    }
    
    #chatbox {
      font: 17px arial, sans-serif;
      //height: 22px;
      width: 100%;
    }
    
    h1 {
      margin: auto;
    }
    
    pre {
      background-color: #f0f0f0;
      margin-left: 20px;
    }
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
    </script>
    <div id='bodybox'>
      <h1>Virtual Assistant</h1>
      <div id='chatborder' class="form-group">
        <p id="chatlog7" class="chatlog">&nbsp;</p>
        <p id="chatlog6" class="chatlog">&nbsp;</p>
        <p id="chatlog5" class="chatlog">&nbsp;</p>
        <p id="chatlog4" class="chatlog">&nbsp;</p>
        <p id="chatlog3" class="chatlog">&nbsp;</p>
        <p id="chatlog2" class="chatlog">&nbsp;</p>
        <p id="chatlog1" class="chatlog">&nbsp;</p>
        <input type="text" name="chat" id="chatbox" placeholder="Hi there! Type here to talk to me." onfocus="placeHolder()" class="form-control">
      </div>

    在 appi.php 我有这段代码

    $p = $_GET['lastUserMessage'];
    //open connection to mysql db
    $connection = mysqli_connect("localhost","username","password","dbname");
    
    //fetch table rows from mysql db
    $sql = "select lastUserMessage, botMessage FROM `table_name` WHERE lastUserMessage='$p'";
    $result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
    
    //create an array
    
    $emparray = $array;
    while($row =mysqli_fetch_assoc($result))
    {
        $emparray = $row;
    }
    echo json_encode($emparray);
    
    //close the db connection
    mysqli_close($connection);
    

    【讨论】:

      猜你喜欢
      • 2013-01-31
      • 2011-02-27
      • 2012-12-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-15
      • 2020-11-02
      • 1970-01-01
      相关资源
      最近更新 更多