显示收到的json数据到html

时间:2014-07-06 07:05:29

标签: json

编程的新手。我现在正确地获取我的json数据我想在html中显示它。 这是我的PHP代码

    <?php
header('Access-Control-Allow-Origin: *');
$con=mysqli_connect("host","user","pass","db");
// Check connection
if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  exit();
}
$callback=$_GET['callback'];
$result = mysqli_query($con,"SELECT * FROM demo");

$var= array();

while($row = mysqli_fetch_assoc($result))
        {
    $var[]=$row;
    }
echo $callback."(".json_encode($var).")";
mysqli_close($con);
?>

这里是java脚本&amp; HTML

<!DOCTYPE html>
<html>
<head>
  <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script>
fname = screen.width;
$.ajax({
    type: 'GET',
    url: "devangpatel.host56.com/sample.php?jsonp=processResults"+"fname="+fname,
    dataType: 'jsonp',
    jsonp: 'callback' ,//jquery will add callback
    jsonpCallback:'processResults'//name of the callback function which server must return
    }); 
    window.processResults = function (response){
    //it must be called with response data inside server answer
    console.log(response);
    }
</script>
</head>
<body>

<h2>AJAX</h2>

<div id="myDiv"></div>

</body>
</html>

还建议一些网站了解如何从服务器获取数据(ajex。)

1 个答案:

答案 0 :(得分:0)

您可以使用jquery html http://api.jquery.com/html/来显示内容

假设回复为

{ "name":"user1" }

您可以将DIV HTML内容设置为

$("#myDiv").html("hello"+response.name);

您还可以查看替代模板引擎http://www.sitepoint.com/10-javascript-jquery-templates-engines/