2014-07-06 92 views
0

新編程.i現在我的json數據正確我想要顯示它在html中。 這裏是我的PHP代碼顯示收到json數據到html

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

ND這裏是Java腳本& 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。)

+0

這又回到一個字符串,所以你只是試圖讓它無論如何顯示在頁面上?下面是你的頁面上的樣子,從服務器'{name:'first',age:10,lived:['Dallas','Boston']}' - 顯然有不同的數據 – Deryck

回答

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/

+0

([{ 「FirstName」:「devang」,「LastName」:「patel」},{「FirstName」:「chetan」,「LastName」:「sh ah」}])這是我的json響應。我把$(「#myDiv」)。html(「hello」+ response.FirstName);在window.processResult()仍然不起作用 – user3790198