摘要

我正在尝试使用ajax在PHP页面上显示数据,以将请求发送到单独的PHP页面,该页面连接并从mysql数据库提取数据。最终结果应该是用户单击按钮,并且无需刷新,数据库中的数据将显示在同一页面上。

档案

displaydata.php


这是客户端看到的页面,并显示数据。


getData.php


这就是连接到MySQL数据库并提取数据的东西。


app.js


这是发出ajax请求的地方。


我的问题

当前,当我运行已有的代码时,单击要调用ajax请求的按钮,页面将刷新,不显示任何数据。

我已经运行它并使用了Inspect元素,发现请求已成功发送,状态为200,我知道可以。在app.js文档的顶部,我设置了console.log(“ app.js found”)以测试文档是否已被读取。这将显示在Inspect元素的控制台中,但是我放置在该函数中的其他console.log()不会显示。



app.js

function init() {
  document.getElementById("Submit").addEventListener('click', ajax);
}

function ajax() {
  console.log("Function started");
  request = new XMLHttpRequest();
  request.open('GET', 'getData.php', true);
  request.onload = function() {
    console.log(request);
    if (request.status >= 200 && request.status < 400){
      // Success!
      document.getElementById("displayData").innerHTML = request.responseText;
    } else {
      // We reached our target server, but it returned an error
    }
  };

  request.onerror = function() {
    // There was a connection error of some sort
  };
  request.send();
  console.log("Request sent");
}
document.addEventListener('load', init);


displaydata.php

<html>
  <head>
    <meta charset="UTF-8">
    <link rel="stylesheet" type="text/css" href="style.css">
    <script src="app.js"></script>
  </head>
 <body>
   <p class='title'>Presenting udp packet data</p><hr />
   <center><div class='data-window'>
   <form id="getSearchNumber">
     <label for="imei">IMEI of desired devices</label>
     <select name="imei" id="imei">
       <option value="Alldata">All Data</option>
       <option value="012981000298213">012981000298213</option>
     </select>
     <br />
     <button id="Submit">Submit</button>
   </form>
   <div id="displayData"></div>
 </body>
 </html>


我知道getData.php代码可以正常工作,但是如果有人希望看到它,请发表评论。

我认为这不是语法错误,而是解决问题的方法中的错误。

最佳答案

在页面中包含jQuery并将<button>更改为<input type="button"只是因为如果使用它将提交表单。

<html>
      <head>
        <meta charset="UTF-8">
        <link rel="stylesheet" type="text/css" href="style.css">
    <script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
        <script src="app.js"></script>
      </head>
     <body>
       <p class='title'>Presenting udp packet data</p><hr />
       <center><div class='data-window'>
       <form id="getSearchNumber">
         <label for="imei">IMEI of desired devices</label>
         <select name="imei" id="imei">
           <option value="Alldata">All Data</option>
           <option value="012981000298213">012981000298213</option>
         </select>
         <br />
         <input type="button" id="Submit" value="Submit"/>
       </form>
       <div id="displayData"></div>
     </body>
     </html>


将您的JS更改为

$(document).ready(function(){
    $( "#Submit" ).click(function() {
        $( "#displayData" ).load( "getData.php" );
    });
})

09-11 17:45
查看更多