分离每个数据

时间:2014-02-19 06:21:07

标签: javascript php jquery ajax

如果我从mySql中检索超过1个数据,我怎么能在我的js文件中分离它。那么我可以在特定位置使用每一段数据吗?

var hr = new XMLHttpRequest();
var pUrl = "../thephp.php";
hr.open("GET", pUrl, true);
hr.setRequestHeader("Contenet-type", "application/x-www-form-unlencoded");

hr.onreadystatechange = function(){
    if(hr.readyState == 4 && hr.status ==200){
        var return_data = hr.responseText;
    }
}
//ASSUMING 'logo1.jpg'  and  'Group Melago' are been sent via the php. how can I define them individually
var image = { 
    'back': { 'url':'img/logo1.jpg', 'img':null },
};
    var group ='Group Melago';

PHP

$query = $db->prepare('SELECT logoImage, groupName FROM sports WHERE eligible = ? ORDER BY RAND() LIMIT 1');
$array = array('N');
$query->execute($array);
$result = $query->fetchAll(PDO::FETCH_ASSOC);
var_dump($result);

2 个答案:

答案 0 :(得分:1)

PHP代码:

$query = $db->prepare('SELECT logoImage, groupName FROM sports WHERE eligible = ? ORDER BY RAND() LIMIT 1');
$array = array('N');
$query->execute($array);
$result = $query->fetchAll(PDO::FETCH_ASSOC);
var $jsonData=json_encode($result )
var_dump($jsonData);

JQUERY CODE:

$.ajax({
     url:"../thephp.php",
     dataType: "json",
     success: 
      function(jsonData) {
          //parse the json data returned from server 
      }
 });

快乐编码:)

答案 1 :(得分:0)

您可以使用jquery AJAX执行此操作。请尝试以下代码,

<强> JQUERY

<script>
$.ajax({
    type:'GET',
    url:'../thephp.php',
    dataType:'json',
    success: function(response){
        var image   =   response[0].logoImage,
            group   =   response[0].groupName;
    }
});
</script>

thephp.php

$query = $db->prepare('SELECT logoImage, groupName FROM sports WHERE eligible = ? ORDER BY RAND() LIMIT 1');
$array = array('N');
$query->execute($array);
$result = $query->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($result);