【问题标题】:Ajax separate data which came from mysql来自mysql的Ajax分离数据
【发布时间】:2014-02-08 15:01:31
【问题描述】:

我正在做这样的 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); 

            });

【问题讨论】:

  • 作为一个初学者,像“json”这样的关键字对我来说毫无意义……也可能是连环杀手或狗。还是谢谢

标签: javascript php jquery mysql ajax


【解决方案1】:

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

【讨论】:

  • hm ajax.php 返回正确的格式。但是 index.html 中的 ajax 调用不起作用:/
  • 我的坏..nervermind :) 现在一切正常。感谢一千次!
【解决方案2】:

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

即代替

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

使用

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

在 ajax 中也将 'dataType' 写为 'json'

【讨论】:

  • 现在我可以使用它了。我如何在 ajax 调用中访问它们?像数据[1],数据[2]..?
  • 没有。您可以使用它的键访问它,例如 data.currentnam、data.currenturl 等等
猜你喜欢
  • 2012-06-09
  • 1970-01-01
  • 2020-08-13
  • 2014-12-15
  • 1970-01-01
  • 2012-06-07
  • 1970-01-01
  • 2016-04-16
  • 2013-10-17
相关资源
最近更新 更多