【问题标题】:How to call PHP file from Javascript and return data from PHP back to Javascript如何从 Javascript 调用 PHP 文件并将数据从 PHP 返回到 Javascript
【发布时间】:2017-04-20 04:24:30
【问题描述】:

我正在寻找最安全的方法来从 Javascript 调用 PHP 文件,然后将数据从 PHP 返回到 Javascript。

我正在开发 Javascript 游戏。我需要调用 PHP 文件来连接数据库并从数据库中选择一些数据。此数据应传递给 Javascript。

我在这里查看了 Chris Baker 的答案:Call php function from javascript

javascript

 // handles the click event for link 1, sends the query
 function getOutput() {
   getRequest(
       'myAjax.php', // URL for the PHP file
        drawOutput,  // handle successful request
        drawError    // handle error
   );
   return false;
 }  
 // handles drawing an error message
 function drawError() {
     var container = document.getElementById('output');
     container.innerHTML = 'Bummer: there was an error!';
 }
 // handles the response, adds the html
 function drawOutput(responseText) {
     var container = document.getElementById('output');
     container.innerHTML = responseText;
 }
 // helper function for cross-browser request object
 function getRequest(url, success, error) {
     var req = false;
     try{
         // most browsers
         req = new XMLHttpRequest();
     } catch (e){
         // IE
         try{
             req = new ActiveXObject("Msxml2.XMLHTTP");
         } catch(e) {
             // try an older version
             try{
                 req = new ActiveXObject("Microsoft.XMLHTTP");
             } catch(e) {
                 return false;
             }
         }
     }
     if (!req) return false;
     if (typeof success != 'function') success = function () {};
     if (typeof error!= 'function') error = function () {};
     req.onreadystatechange = function(){
         if(req.readyState == 4) {
             return req.status === 200 ? 
                 success(req.responseText) : error(req.status);
         }
     }
     req.open("GET", url, true);
     req.send(null);
     return req;
 }

HTML

 <a href="#" onclick="return getOutput();"> test </a>
 <div id="output">waiting for action</div>

PHP

 // file myAjax.php
 <?php
   echo 'hello world!';
 ?>

但我需要检索总共 4 个变量:1 个问题和 3 个答案,根据 Chris 的回答它只获取 1 个回声。

我的 PHP 文件是这样的:

//some code
$questions->bind_result($question, $answer1, $answer2, $answer3);

while ($questions->fetch()) {
    echo $question;  
    echo $answer1;
    echo $answer2;
    echo $answer3;
}

我的 HTML + Javascript 文件:

<div class="question-area">

</div>
<div class="answers">
     <input type="button" class="btn" value="return getSuccessOutput();">   

     <input type="button" class="btn" value="return getSuccessOutput();">   

     <input type="button" class="btn" value="return getSuccessOutput();">   
     <span id="output" class="output"></span>
</div>

我需要将$question 变量传递给.question-area$answer1$answer2$answer3 到按钮的值。你能帮我实现它吗?

更新

这是我的connect.php,当我尝试刷新 www.mywebsite/connect.php 时,它大多数时候什么都不返回(空白页),刷新 ~10 次后它会选择随机数据。它有什么问题? SQL 查询似乎不错,在 phpMyAdmin 中工作正常。

$questions = $con->prepare("
    SELECT Question, Answer1, Answer2, Answer3
    FROM Questions AS q
    ORDER BY RAND()
    LIMIT 1
"); 
$questions->execute();

$questions->bind_result($question, $answer1, $answer2, $answer3);

while ($questions->fetch()) {
    $qa = array('question' => $question, 'a1' => $answer1, 'a2' => $answer2, 'a3' => $answer3);
    echo json_encode($qa);
}

如果我在 while 循环中传递var_dump($qa); 它总是返回数据。 echo json_encode($qa)有问题

【问题讨论】:

  • 你应该发送一个 JSON 对象。
  • “安全”是什么意思?
  • @SLaks 我已经更新了我的问题。 PHP文件有问题,而我正在使用json_encode($qa)。你有什么想法吗?
  • 您必须发出单个 JSON 对象;你不能连接 JSON。你可能想要一个数组。
  • @SLaks 在我的 PHP 文件中 $qa 是包含 1 个问题和 3 个答案的数组。我正在尝试刷新我的 connect.php 文件,有时它返回数组,有时它什么也不返回。

标签: javascript php jquery html node.js


【解决方案1】:

将您的数据放入一个数组并回显 json。

$qa = array('question' => $question, 'a1' => $answer1, 'a2' => $answer2, 'a3' => $answer3);
echo json_encode($qa);

现在在您的 JS 中,您将可以访问具有相同键的对象。

【讨论】:

  • 谢谢你的回答,我现在如何通过JS访问它?我正在尝试这样document.btn1.innerHTML = a1;,但出现错误:Uncaught ReferenceError: a1 is not defined
  • @Infinity:这为您提供了一个具有属性的对象。您需要使用这些属性(您还需要解析 JSON)。使用您的调试器查看您的 Javascript 有什么。
  • @SLaks 我尝试使用var test = JSON.parse(qa); document.btn1.innerHTML = test;,但在这种情况下我得到了一个错误:(index):10 Uncaught ReferenceError: qa is not defined。如果我使用var test = JSON.parse(a1); document.btn1.innerHTML = test;,我会收到一个错误:Uncaught ReferenceError: a1 is not defined。解析 JSON 有什么问题?
  • @Infinity 你在用 Jquer 吗?如果你是,那么你可以简化很多这样的代码。如果没有,请删除标签。一旦你让我知道我可以使用什么,我会更新我的答案。
  • @Infinity:那你应该打电话给$.getJSON()
猜你喜欢
  • 2013-03-29
  • 1970-01-01
  • 2010-10-15
  • 2011-08-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多