简体   繁体   English

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

[英]Retrieving multiple data with mysql json, ajax

I am Posting my values from database here, code: 我在这里从数据库发布我的值,代码:

<?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);
?>

Then I am trying to write out all rows of my array but can't get to understand how. 然后,我试图写出数组的所有行,但无法理解如何做。 However, this is the code from my script. 但是,这是我脚本中的代码。 Hope you can help somehow. 希望您能以某种方式提供帮助。 Thanks. 谢谢。

<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>

I can't find a solution so I am very greatful for good and simple answers! 我找不到解决方案,所以我非常希望获得好的简单答案!

In PHP file do it: 在PHP文件中执行以下操作:

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

echo json_encode($dataArray);

AND in JS: 在JS中:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM