ajax PHP MySQL query

ajax PHP MySQL query

本文关键字:query MySQL PHP ajax      更新时间:2023-09-26

我需要ajax调用的帮助,但我是ajax的新手,我不确定该怎么做。

我有以下PHP代码(电话.php):

<?php
$con = mysqli_connect('localhost','root','root','mydb');
if (!$con) {
    die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"mydb");
$sql="SELECT * FROM incoming_calls";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)) {
    $callArray[] = array('phonenumber' => $row['phone_number'], 'id' => $row['phone_login_id']);
        print "<div id='"call'">";
        print_r($callArray);
        print "</div>"
}
mysqli_close($con);
?>

我想在将新内容发布到表格时自动实时更新页面。

这是我的非工作页面:

<!DOCTYPE html> 
<html lang="en"> 
<head> 
<meta charset="utf-8"> 
<title>Phone calls</title> 
</head>
<body>
<script language="javascript" type="text/javascript">
<!-- 
//Browser Support Code
function ajaxFunction() {
  var ajaxRequest;
  try {
      // Opera 8.0+, Firefox, Safari
      ajaxRequest = new XMLHttpRequest();
  } catch (e) {
      // Internet Explorer Browsers
      try {
        ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
      } catch (e) {
          try {
            ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
          } catch (e) {
            // Something went wrong
            alert("Your browser broke!");
            return false;
          }
      }
  }
  ajaxRequest.onreadystatechange = function(){
  var ajaxDisplay = document.getElementById('call');
  ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
setInterval(function() { //Broken
    ajaxRequest.open();  //Not sure what to put here.
}, 1000);
}
//-->
</script>
</body>
</html>

您的 ajaxRequest.open() 方法采用 3 个参数,根据 XMLHttpRequest 规范:

  • 请求的方法(POST、GET 等)
  • 您要向其发送请求的文件
  • 请求是否异步。

所以:

ajaxRequest().open('GET','yourfile.php',true);

将构建一个异步 GET 请求到你的文件.php。

你还缺少 ajaxRequest().send(),它实际上会把你的请求发送到服务器。

有很多关于这个的知识,所以我建议谷歌搜索它,因为你似乎缺乏基础知识。