简体   繁体   English

使用ajax在表中显示JSON数据(来自php文件)

[英]show JSON data(from php file) in table using ajax

I hava a php code as shown below serverdata.php 我哈瓦一个PHP代码如下所示serverdata.php

<?php

require_once('database.php');
header("Content-type: application/json");  

$sql = "SELECT * FROM user";
$result = mysql_query($sql);
$uid = array();
$uname = array();


while($row = mysql_fetch_assoc($result)) 
   {
     $dataarray[] = $row;
   }

  echo json_encode($dataarray); 
?>

which produce the following output in JSON format: 会产生以下JSON格式的输出:

[{"id":"1","username":"Sagun","password":"61b51ae250c7e7505191e4d5e6240c04"},{"id":"2","username":"roshan","password":"d6dfb33a2052663df81c35e5496b3b1b"},{"id":"17","username":"rajiv","password":"9a9af43c15771eaf3b2db8bb28a2829d"}]

All i want is to get the data from above php file that is in json format and display it in table in another page using AJAX. 我想要的只是从上面json格式的php文件中获取数据,并使用AJAX将其显示在另一页的表中。 Please guide me through it. 请指导我。

 ID USERNAME PASSOWRD 
  1   sagun   61b51...    
  2   roshan  d6dfb.. 
 17   rajiv   9a9af..

This is the ajax function to get your json data from php output, try to modify as you need. 这是ajax函数,可从php输出获取json数据,尝试根据需要进行修改。

<script type="text/javascript">
$(function() {
    $.ajax({
        type      : 'POST',
        url       : 'YOUR_PHP_URL',
        data      : {},
        dataType  : 'json',
        error     : function (a, b, c) 
        {

        },
        success   : function(data) 
        {
            console.log( data );
        }
    });
});
</script>

Don't forget to include the jQuery library. 不要忘记包括jQuery库。 https://developers.google.com/speed/libraries/#jquery https://developers.google.com/speed/libraries/#jquery

This code for build table in jquery 这段代码用于在jquery中构建表

<script type="text/javascript">
function jsonData()
{

    $.ajax({
        type:'post',
        url:"serverdata.php",
        datatype:'json',
        success:function(data)
        {
            var jdata=$.parseJSON(data);
            ///console.log(jdata);
            $(function(){
                $.each(jdata,function(i,item){
                    var tr = $('<tr>').append(
                    $('<td>').text(item.id),
                    $('<td>').text(item.name),
                    $('<td>').text(item.email),
                    //$('<td>').text(item.password),
                    $('<td>').text(item.mob_num),

                );
                $("#tableId tbody").append(tr); 
                //console.log(tr.wrap('<p>').html());
                })
            })

        }
    })
}

database.php database.php

    <?php
try{
    $db = new PDO('mysql:host=localhost;dbname=testing', "root" , "");


}catch(PDOException $e){
    print "error in connection" . $e->getMessage();
}

home.html home.html

    <!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>JSON data</title>
</head>
<body>

  <table id="demoTable">
    <thead>
      <tr>
        <td ><label>Id</label></td>
        <td ><label>Username</label></td>
        <td ><label>Password</label></td>
      </tr>
    </thead> 
    <tbody>  
    </tbody>  
  </table>
  <script src="jquery.min.js" type="text/javascript"></script>
  <script src="detail.js" type="text/javascript"></script>
</body>
</html>

details.js details.js

$(document).ready(function() {

    $.ajax({
        url:'serverdata.php',
        type:'POST',
        success:function(data){

            var result = $.parseJSON(data);
            $.each(result, function(key, value){
                $.each(value, function(k, v){
                    if(k === "id"){
                        $("#demoTable >tbody:last").append(
                            $('<tr>').append(
                                $('<td>').append(v)
                                .append(
                                    $('</td>').append(
                                        $('</tr>')
                                        )
                                    )
                                )
                            );
                    }
                    if(k === "username"){
                        $("#demoTable >tbody >tr:last").append(

                            $('<td>').append(v)
                            .append(
                                $('</td>')

                                )

                            );
                    }
                    if(k === "password"){
                        $("#demoTable >tbody >tr:last").append(

                            $('<td>').append(v)
                            .append(
                                $('</td>')

                                )

                            );
                    }
                });
            });
        }
    })      
});

serverdata.php serverdata.php

<?php
require_once 'database.php';
$data = array();
$stmt = $db->query('SELECT * FROM user');
$row = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($row as $key => $value) {
    $data[$key] = $value;
    $result = json_encode($data);
}
echo $result; 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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