将已解析的JSON插入到html中

时间:2013-07-27 08:21:39

标签: php jquery ajax json

我尝试了许多方法,从教程和其他问题发布但似乎没有任何效果。我试图通过jquery将数据从php发送到div和变量。我在php端设置了数组,一切正常但在jquery方面我总是得到一个意外的标识符错误或div留空或两者

var var_numdatacheck  = <?php echo $datacheck; ?>;
  var var_rowtest = parseInt(var_numdatacheck);
 function waitupdate(){
 $.ajax({
          type: 'POST',
          url: 'update.php',
          data: {function: '3test', datacheck: var_rowtest},
         dataType: "json",
          success: function(check) {
            var data = JSON.parse(check);
                var_rowtest = data[id]; // sets the variable numcheck as the new id number            
                    $('#datacheck').html(data[0]); // I've confirmed data[0] has a value but the div is left blank


            }

  error: function(msg) {
     console.log(msg)// here i get an unexpected identifier error 
  }

        });
    }   


  $(document).ready(function()  {
     waitupdate();
  });

php的输出是

{"id":"4","0":"Name"}

这是实际的PHP代码

<?php
require "dbc.php";

    $function = $_POST['function'];
    $datacheck = $_POST['datacheck'];
    $search="SELECT * FROM Feedtest ORDER BY id DESC";
    $request = mysql_query($search);
    $update= mysql_fetch_array($request);
    $updateid = $update['id'];
    $updatecheck = mysql_num_rows($request);
    $data = array();



    if ($function == $datacheck){
    echo $updatecheck;
    echo $datacheck;
    }

    if ($function == "3test" && $updatecheck > $datacheck )      {    
     $updatesearch="SELECT * FROM Feedtest WHERE id = '$updateid' ORDER BY id DESC";
    $updatequery = mysql_query($updatesearch);
    $check['id'] = $updateid;
    while ($row = mysql_fetch_array($updatequery)){
  ?>

 <?php $check[]= $row['First Name']; ?>
<?php
}

echo json_encode($check); 
} 
?>
</div>
</ul>

2 个答案:

答案 0 :(得分:1)

这对你有用,

var var_rowtest = data['id'];
var value= data[0];

根据需要在div中设置变量var_rowtestvalue

我猜var_rowtest = data[id];不是正确的语法,请使用上面的语法

答案 1 :(得分:1)

请尝试更改您的变量名称,$ .ajax中声明的错误函数为我抛出了一个JS错误。

另一件不必要的事情是JSON.parse - 我使用名为“update.php”的PHP脚本返回正确的标题:

<?php header('content-type: application/json');?>

此代码有效:

var numDataCheck = 1,
    rowTest = parseInt(numDataCheck);
function waitupdate() {
    $.ajax({
        type: 'POST',
        url: 'update.php',
        data: {function: '3test', datacheck: rowTest}, dataType: "json",
        success: function(data) {               
            rowTest = data.id;
            $('#datacheck').html(data[0]);  
        }
    });
}

$(document).ready(function() {
    waitupdate();
});