gpt4 book ai didi

php - 使用 mysql json,ajax 检索多个数据

转载 作者:行者123 更新时间:2023-11-29 03:03:46 25 4
gpt4 key购买 nike

我在这里从数据库中发布我的值,代码:

<?php 
$host = "localhost";
$user = "root";
$pass = "";

$databaseName = "ani";
$tableName = "balls";

//--------------------------------------------------------------------------
// 1) Connect to mysql database
//--------------------------------------------------------------------------
include 'DB.php';
$con = mysql_connect($host,$user,$pass);
$dbs = mysql_select_db($databaseName, $con);

//--------------------------------------------------------------------------
// 2) Query database for data
//--------------------------------------------------------------------------
$result = mysql_query("SELECT * FROM $tableName");
$array = mysql_fetch_row($result);

//echo json
echo json_encode($array);
?>

然后我试图写出数组的所有行,但无法理解如何写出。但是,这是我脚本中的代码。希望你能以某种方式提供帮助。谢谢。

<script id="source" language="javascript" type="text/javascript">

setInterval("yourAjaxCall()",1000);
function yourAjaxCall()
{
$.ajax({
url: 'api.php', //the script to call to get data
data: "id=1", //you can insert url argumnets here to pass to api.php
//for example "id=5&parent=6"
dataType: 'json', //data format
success: function(data) //on recieve of reply
{
var id1 = data[0]; //get id of first row
var vcolor1 = data[1]; //get color of first row
$("#square").css({"background-color" : vcolor1});
$color1 = vcolor1; //saving value
var $color1;

//HERE I WANT TO BE ABLE TO GET NEXT ROW OF MY JSON ARRAY. HOW?
}
});
};

</script>

我找不到解决方案,所以我非常感谢简单的好答案!

最佳答案

在 PHP 文件中执行:

$result = mysql_query("SELECT * FROM $tableName");         
$dataArray = array();
while($array = mysql_fetch_assoc($result)){
$dataArray[] = $array;
}

echo json_encode($dataArray);

在 JS 中:

success: function(data)
{
var obj = JSON.parse(data);
$.each(obj,function(index,value)){
alert(index+" : "+value); //here you can get all data
}
}

关于php - 使用 mysql json,ajax 检索多个数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19027411/

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