Reputation: 49
I want to use .getJSON to get data from server. The data can get, but it can not display in page.
js code:
$(function(){
alert(1);
$("#jsondata").bind("click",function()
{
var data = "action=getdata";
alert(2);
$.getJSON("Guess.php",data, function(json)
{
alert(3);
var str = '<table><tr><td>Name</td><td>1#Sex</td><td>2#Tel</td></tr>';
$.each(json,function(i,v){
str += '<tr><td>'+v.name+'</td><td>'+v.sex+'</td><td>'+v.tel+'</td></tr>';
});
str += '</table>';
$("#datashow").append(str);
});
});
});
html code:
<button id="jsondata" name="jsondata" accesskey="g">GetData</button>
<div id="datashow"></div>
The data I got from server display in fire bug: {"name":"Tom","sex":"male","tel":"456","email":"[email protected]"}
Upvotes: 0
Views: 80
Reputation: 997
Try the following code.
$.getJSON("Guess.php",data, function(json) {
// Convert json reponse object to array
json = $.makeArray(json);
var str = '<table><tr><td>Name</td><td>1#Sex</td><td>2#Tel</td></tr>';
$.each(json,function(i,v){
str += '<tr><td>'+v.name+'</td><td>'+v.sex+'</td><td>'+v.tel+'</td></tr>';
});
str += '</table>';
$("#datashow").append(str);
});
});
Upvotes: 0
Reputation: 796
The json parameter for success function should already be parsed as JSON, so loop with a normal loop:
$(function(){
alert(1);
$("#jsondata").bind("click",function()
{
var data = "action=getdata";
alert(2);
$.getJSON("Guess.php",data, function(json)
{
alert(3);
var str = '<table><tr><td>Name</td><td>1#Sex</td><td>2#Tel</td></tr>';
for(var i in json) {
str += '<tr><td>' + i.name + '</td><td>' + i.sex + '</td><td>' + i.tel + '</td></tr>';
}
str += '</table>';
$("#datashow").append(str);
});
});
});
Upvotes: 1
Reputation: 11717
Try this: (There is no need to loop with $.each
)
$(function () {
$("#jsondata").bind("click", function () {
var data = "action=getdata";
$.getJSON("Guess.php", data, function (json) {
var str = '<table><tr><td>日期</td><td>1#铸机产量</td><td>2#铸机产量</td></tr>';
str += '<tr><td>' + json.name + '</td><td>' + json.sex + '</td><td>' + json.tel + '</td></tr>';
str += '</table>';
$("#datashow").append(str);
});
});
});
Upvotes: 0