简体   繁体   中英

Use jquery to get jsondata

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":"sdfd@15.com"}

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM