Ajax分离来自mysql的数据

时间:2014-02-08 15:01:32

标签: javascript php jquery mysql ajax

我正在做这样的ajax调用:

                function myCall() {
                var request = $.ajax({
                    url: "ajax.php",
                    type: "GET",           
                    dataType: "html"
                });

                request.done(function(data) {
                    $("image").attr('src',data);   


                });

                request.fail(function(jqXHR, textStatus) {
                    alert( "Request failed: " + textStatus );

                });         
            }

这是我的ajax.php:

 <?php
 $connection = mysql_connect ("",
 "", "");

 mysql_select_db("");

// QUERY NEW ONE
$myquery = "SELECT * FROM mytable ORDER BY rand() LIMIT 1";
$result = mysql_query($myquery);
while($row = mysql_fetch_object($result))
{
$currentid = "$row->id";
$currentname = "$row->name";
$currenturl = "$row->url";
$currentimage = "$row->image";
echo  $currenturl,$currentnam, $currenturl,$currentimage;

}

mysql_close($connection);
?>

来自ajax调用的我的数据变量现在包含所有变量:

($currenturl,$currentnam, $currenturl,$currentimage)

我如何将它们分开,以便我可以执行以下操作:

 request.done(function(data) {
                $("id").attr('src',data1);   
                $("name").attr('src',data2); 
                $("url").attr('src',data3);   
                $("image").attr('src',data4); 

            });

2 个答案:

答案 0 :(得分:2)

jQuery:

 $.ajax({

    type:"POST",
    url:"ajax.php",
    dataType:"json",
    success:function(response){

    var url = response['url'];

    var name = response['name'];

    var image = response['image'];

   // Now do with the three variables



   // $("id").attr('src',data1);   
   // $("name").attr('src',data2); 
  //  $("url").attr('src',data3);   
   // $("image").attr('src',data4);

    },
    error:function(response){

    alert("error occurred");
    }

    });

从你的代码:

echo  $currenturl,$currentnam, $currenturl,$currentimage;

将以上代码替换为以下代码:

$array = array('url'=>$currenturl, 'name'=>$currentname, 'image'=>$currentimage);

echo json_encode($array);

答案 1 :(得分:1)

而不是字符串返回一个数组,即使用json类型返回值

,而不是

echo  $currenturl,$currentnam, $currenturl,$currentimage;

使用

echo json_encode array('current' => $currenturl,'currentnam' => $currentnam, 'currenturl' => $currenturl,'currentimage' => $currentimage);

并在'ajax

中将'dataType'写为'json'