gpt4 book ai didi

javascript - "$.get"用于检索信息

转载 作者:行者123 更新时间:2023-11-29 02:23:31 24 4
gpt4 key购买 nike

我正在尝试让一个简单的 javascript 弹出脚本在数据库实时更新时运行。我不确定下一步该做什么,因为我仍然是 jQuery 和 ajax 的新手,但下面的代码是我现在拥有的:

PHP MySQL查询页面:

<?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']);
if(!empty($row)) {
$number = $row['phone_number'];
}
}

$sql="SELECT Username, Password FROM tblUsers WHERE PhoneHome='$number' OR PhoneCell='$number' OR PhoneWork='$number'";
$result = mysqli_query($con,$sql);

while($row = mysqli_fetch_array($result)) {
$userArray = array("username" => $row['Username'], "password" => $row['Password']);
//echo json_encode($userArray);
}
echo json_encode($userArray);

mysqli_close($con);
?>

HTML 页面:

<!DOCTYPE html> 
<html lang="en-US">
<head>
<meta charset="utf-8">
<title>Phone calls</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<script language="javascript" type="text/javascript">
function getCall(){
$.get("phonecall.php", function(data){
var loginInfo = jQuery.parseJSON(data);
var user = loginInfo.username;
var pass = loginInfo.password;
$('#username').html(user);
$('#password').html(pass);
});

/*$.getJSON("phonecall.php", function(data){
for (var i=0, len=data.length; i < len; i++) {
$('#username').html(data);
}
});*/
}
setInterval(getCall,5000);
</script>

<div id="username"></div>
<div id="password"></div>
</body>
</html>

我遇到的一个问题是,当有 2 个或更多用户使用相同的电话号码(例如家庭电话)时,根据 json_encode 的位置,将返回表中的最后一个条目,或者返回什么都没有。如果 json_encode 在 while 循环中,我可以检查控制台,它说正在检索信息,但我的“$.get”语法一定不正确,以允许显示多个条目。有什么想法吗?

最佳答案

你只会保存一行数据:

while($row = mysqli_fetch_array($result)) {
$userArray = array("username" etc...
^^^^---here

如果您有多行数据,您获取的每一行都会覆盖 $userArray 中的前一行。

你可能想要

$userArray[] = array("username" etc...
^^---- note these

因此您正在创建一系列结果。

您还必须修改您的 JS 代码以接受一组数组,因为现在您只处理一个用户名/密码。

关于javascript - "$.get"用于检索信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27513632/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com