通过ajax将数据添加到div

时间:2014-07-13 18:29:00

标签: php ajax json mysqli

下午

我的php和Ajax现在几乎已经完成了,但是我坚持一件事我将数据发送回ajax,但它只在我指定的div中显示[object Object]并且我'我希望发回的结果数量在那里。

<?  $call="SELECT * FROM notifications WHERE notification_targetuser='$user1_id' ORDER BY notification_id DESC LIMIT 1";
        $chant=mysqli_query($mysqli,$call) or die(mysqli_error($mysqli));
        $num=mysqli_num_rows($chant);


            while($notification_id=mysqli_fetch_array($chant))
            {
            ?>
            <script type="text/javascript">
setInterval(function(){


  var notification_id="<?php echo $notification_id['notification_id'] ;?>"

$.ajax({
type: "GET",
url: "viewajax.php?notification_id="+notification_id,   
dataType:"json",
cache: false,
success: function(response){
$("#mes").prepend(response);

}
});
},20000);

</script>
<? }?>

Vuewajax.php

<?php

 include"database.php";

if(isset($_GET['notification_id'])){

$id=$_GET['notification_id'];
$user1_id=$_SESSION['id'];
$json = array();
$com=mysqli_query($mysqli,"select notification_id from notifications where notification_id > '$id'");
echo mysqli_error($mysqli);

$num = mysqli_num_rows($com);
if($num>0){

    echo '<span id="mes">'.$num.'</span>';
}
$resultArr = mysqli_fetch_array($com);
$json['notification_id'] = $resultArr['notification_id'];

mysqli_free_result($com);


echo json_encode($json);
}
 ?>

我在firebug中的回复

<span id="mes">1</span>{"notification_id":"3306"}

2 个答案:

答案 0 :(得分:1)

您正在返回一个json对象,因此您需要访问正确的属性,在本例中为notification_id。设置正确的内容类型标题也是一种很好的做法:

//php set json header
header('Content-Type: application/json');
echo json_encode($json);

//js access property of returned object
$("#mes").prepend(response.notification_id);

根据评论编辑 - 如果你发送json,只发送json,而不是混合在html中:

if($num>0){

    $json['num'] = $num;
}else{
    $json['num'] = 0;
}
$resultArr = mysqli_fetch_array($com);
$json['notification_id'] = $resultArr['notification_id'];

mysqli_free_result($com);
header('Content-Type: application/json');
echo json_encode($json);


//js
 $("#mes").prepend('<span id="mes">'+ response.num + '</span>');

进一步编辑 您可以检查num的值,并且仅在它不为0时才前置。当0的计算结果为false时,以下内容将起作用

if(response.num){
     $("#mes").prepend('<span id="mes">'+ response.num + '</span>');
}

答案 1 :(得分:1)

这个答案似乎是偏离主题的,但您向我们展示的代码并不安全。他容易轻松sql injection

例如:

$id  = $_GET['notification_id'];
$com = mysqli_query($mysqli,"select notification_id from notifications where notification_id > '$id'");

注射&#34; &#39 ;;删除用户WHERE 1或用户名=&#39;&#39; &#34;在你的notification_id参数中将删除所有用户!

使用prepared statementsXKCD更容易,更安全; - )