如何使用jquery中的Ajax从Json发送html元素的数据?

时间:2022-12-08 11:33:55

I am trying to show data from 5 rows of Database (MySQL) to rows of table using on success of jQuery AJAX call. The data is in JSON format.

在jQuery AJAX调用成功的情况下,我正在尝试从数据库(MySQL)的5行到表的行显示数据。数据是JSON格式。

Issue: I am not able to figure out to get all of those rows. I can get only one row but console showed me all the rows in JSON format.

问题:我不能弄明白所有这些行。我只能得到一行,但是console显示了JSON格式的所有行。

$.ajax({
  url: '<?php echo base_url('ads/select_post'); ?>',
   data: {},
   dataType: "json",
   cache: false,
   success: function (data) {
     $.each(data, function (i, val) { 
       console.log(val.name);
       $("#name").html(val.name);
       $("#price").html(val.price);
       $("#addr").html(val.addr);
       $("#des").html(val.des);
       $("#viewed").html(val.viewed);
       $("#status").html(val.status);
    });
 }
});

Console output:

控制台输出:

[{"name":"dfasdfas","price":"0","addr":"dfasdfas","des":"sadfdfasdfasdf","viewed":"0","img":"","status"
:"1"},{"name":"Heng","price":"0","addr":" dflkas;df","des":"asdfasdf"
,"viewed":"0","img":"","status":"1"},{"name":"asdDasdA","price":"0","addr":"asdADasd","des":"ASDasdASD"
,"viewed":"0","img":"","status":"1"},{"name":"asdfas","price":"0","addr":"fasdfas","des":"dfasdf","viewed"
:"0","img":"","status":"1"},{"name":"asdf","price":"0","addr":"asdfasdfas","des":"asdfasdfasdf","viewed"
:"0","img":"","status":"1"}]

HTML of the table i am sending data to,

我要发送数据到的表格的HTML,

<tbody id="items">
 <tr>
  <td>1</td>
  <td><a><div id="name"></div> </a></td> 
  <td><a><div id="price"></div> </a></td> 
  <td><a><div id"addr"></div></a></td> 
  <td><div id="des"></div> </td> 
  <td><a><div id="viewed"></div></a></td> 
  <td><a><div id="status"></div></a></td> 
 </tr>

Please advise.

请建议。

10 个解决方案

#1


10  

Lots of good answers, but since I've created an example I'll post that too. If nothing else it might give you, or someone else, an alternative solution. I'm using classes instead of Id's, and keep your original structure.

有很多很好的答案,但是既然我已经创建了一个示例,我也将发布它。如果没有别的东西,它可能会给你或者其他人一个替代的解决方案。我使用的是类而不是Id,并且保持原来的结构。

Since this was accepted as answer I should also mention why your code failed:
Your each loop is continually overwriting the contents of your table row data, instead of creating new rows. Another thing that needed fixing is that you had given the columns Id's, and those cannot stay (as they were) if you want to repeat the rows, since Id's within a page must be unique.

由于这被接受为答案,我还应该提到代码失败的原因:您的每个循环不断覆盖表行数据的内容,而不是创建新的行。另一个需要修改的地方是,您已经给定了列Id,如果您想重复行,那么它们就不能停留(就像它们一样),因为Id在一个页面中必须是惟一的。

There are many methods to create new elements. I chose clone() as I figure you would always have a row for header that could easily be used to clone/copy. Also I added a unique Id attribute to each tr. These are not really used in the current implementation below, but it might be good to have as reference later in your project.

有许多方法可以创建新元素。我选择了clone(),因为我认为您总会有一个用于header的行,可以很容易地用于克隆/复制。我还为每个tr添加了一个唯一的Id属性,这些属性在下面的当前实现中并没有真正使用,但是最好在以后的项目中使用它们作为参考。

var data = [{"name":"dfasdfas","price":"0","addr":"dfasdfas","des":"sadfdfasdfasdf","viewed":"0","img":"","status"
:"1"},{"name":"Heng","price":"0","addr":" dflkas;df","des":"asdfasfasdfasdfasdfasdfasfasdfasdfasdfas"
,"viewed":"0","img":"","status":"1"},{"name":"asdDasdA","price":"0","addr":"asdADasd","des":"ASDasdASD"
,"viewed":"0","img":"","status":"1"},{"name":"asdfas","price":"0","addr":"fasdfas","des":"dfasdf","viewed"
:"0","img":"","status":"1"},{"name":"asdf","price":"0","addr":"asdfasdfas","des":"asdfasdfasdf","viewed"
:"0","img":"","status":"1"}];

//place within the Ajax success
$.each(data, function(i, val) {
  var currRow = $("#tr0").clone().appendTo($('#items')).attr('id','tr' + (i + 1));
  currRow.find('td:eq(0)').html(i + 1);
  currRow.find('.name').html(val.name);
  currRow.find('.price').html(val.price);
  currRow.find('.addr').html(val.addr);
  currRow.find('.des').html(val.des);
  currRow.find('.viewed').html(val.viewed);
  currRow.find('.status').html(val.status);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
  <tbody id="items">
    <tr id="tr0">
      <td>Id</td>
      <td><a><div class="name">Name</div></a></td>
      <td><a><div class="price">Price</div></a></td>
      <td><a><div class="addr">Addr</div></a></td>
      <td><div class="des">Des</div></td>
      <td><a><div class="viewed">Viewed</div></a></td>
      <td><a><div class="status">Status</div></a></td>
    </tr>
  </tbody>
</table>

#2


5  

You can try this, I test it locally and it works:

你可以试试这个,我在本地测试,它是有效的:

$.ajax({
    url: '<?php echo base_url('ads/select_post'); ?>',
    data: {},
    dataType: "json",
        cache: false,
        success: function (data) {
        $.each(data, function (i, val) {
            var tr = "<tr>" +
                "<td>"+ (i + 1) + "</td>" +
                "<td>"+ val.name + "</td>" +
                "<td>"+ val.price + "</td>" +
                "<td>"+ val.addr + "</td>" +
                "<td>"+ val.des + "</td>" +
                "<td>"+ val.viewed + "</td>" +
                "<td>"+ val.status + "</td>" +
                "</tr>";
            $(tr).appendTo("tbody");
        });
    }
});

And your html table:

和你的html表:

<table>
    <tbody id="items">

    </tbody>
</table>

#3


5  

You need something like this:

你需要这样的东西:

DEMO HERE

演示

HTML Structure

HTML结构

<table>
    <thead>
        <th>Sl No.</th>
        <th>Address</th>
        <th>Description</th>
        <th>Image</th>
        <th>Name</th>
        <th>Price</th>
        <th>Status</th>
        <th>Viewed</th>
    </thead>
    <tbody id="items">
    </tbody>
</table>

JS

JS

    $.each(data, function (i, val) { 
           $("tbody#items").append("<tr><td>"+(i+1)+"</td><td><a><div>"+val.addr+"</div></a></td>"
                +"<td><a><div>"+val.des+"</div></a></td>"
                +"<td><a><div>"+val.img+"</div></a></td>"
                +"<td><a><div>"+val.name+"</div></a></td>"
                +"<td><a><div>"+val.price+"</div></a></td>"
                +"<td><a><div>"+val.status+"</div></a></td>"
                +"<td><a><div>"+val.viewed+"</div></a></td></tr>");
    });

#4


5  

You need to create table rows() in the ajax success.
And you should not use same ids in the td tags.

您需要在ajax成功中创建表行()。你不应该在td标签中使用相同的id。

var html = "";
$.ajax({
  url: '<?php echo base_url('ads/select_post'); ?>',
   data: {},
   dataType: "json",
   cache: false,
   success: function (data) {
     $.each(data, function (i, val) { 
        console.log(val.name);

        html +="<tr>";
        html += "<td>" + val.name + "</td>" ;
        html += "<td>" + val.price + "</td>" ;
        html += "<td>" + val.addr + "</td>" ;
        html += "<td>" + val.des + "</td>" ;
        html += "<td>" + val.viewed + "</td>" ;
        html += "<td>" + val.status + "</td>" ;
        html +="</tr>";
    });
    $("$items").html(html);
  }
});

Your html:

html:

<table>
    <tbody id="items">

    </tbody>
</table>

#5


3  

You probably need some code like this, This is rough idea you can let me know if you don't get it

你可能需要一些像这样的代码,这是一个粗略的想法,如果你不理解,可以告诉我

this.tableElement = jQuery('<table/>', {
}).appendTo(gridWrapElement);

var tableBody = jQuery('<tbody/>', {
    'class': 'eg-table-body'
});

this.tableBodyRow = jQuery('<tr/>', {
});

var scope = this;
var columns = [{
        name:"Name",
        dataIndex:"name",
        width: "33%"
    },{
        name:"Price",
        dataIndex:"price",
        width: "33%"
    },{
        name:"Address",
        dataIndex:"addr",
        width: "34%"
    }];
$.each(this.columns, function(index, column) {
    var tableBody = jQuery('<td/>', {
        width: column.width,
        columnDataIndex: column.dataIndex,
        columnIndex: index
    });

    jQuery('<div/>', {
        html: "<a>" + column.name + "</a>",
        class: "eg-table-Body-div"
    }).appendTo(tableBody);

    tableBody.appendTo(scope.tableBodyRow);
    scope.tableBodyItems.push(tableBody);
});

jQuery(this.tableBodyRow).appendTo(tableBody);
jQuery(tableBody).appendTo(this.tableElement);

#6


3  

var body = '';
$.each(val,function(i,j){
  body = body + '<tr><td>'+i+1+'</td>';
  body = body + '<td>'+j.name+'</td>';
  body = body + '<td>'+j.price+'</td>';
  body = body + '<td>'+j.addr+'</td>';
  body = body + '<td>'+j.des+'</td>';
  body = body + '<td>'+j.viewed+'</td>';
  body = body + '<td>'+j.status+'</td></tr>';
});
$('#items').html(body);

This will give you the table with values

这将为您提供具有值的表

#7


3  

It is better if you can rows dynamically. Then append generated html into tbody table like example below :

如果可以动态地行,那就更好了。然后将生成的html添加到如下示例所示的tbody表中:

HTML

HTML

<table>
<tbody id="items">
    <tr>
        <td>No.</td>
        <td>name</td>
        <td>price</td>
        <td>addr</td>
        <td>des</td>
        <td>viewed</td>
        <td>status</td>
    </tr>
</tbody>

JS

JS

var data = [{
"name": "dfasdfas",
    "price": "0",
    "addr": "dfasdfas",
    "des": "sadfdfasdfasdf",
    "viewed": "0",
    "img": "",
    "status": "1"
}, {
"name": "asdDasdA",
    "price": "0",
    "addr": "asdADasd",
    "des": "ASDasdASD",
    "viewed": "0",
    "img": "",
    "status": "1"
}];

/************ put this inside ajax success block*/
var output;
$.each(data, function (i, val) {
output += '<tr><td>' + i + '</td>' +
    '<td><a><div id="name">' + val.name + '</div> </a></td>' +
    '<td><a><div id="price">' + val.price + '</div> </a></td>' +
    '<td><a><div id"addr">'+ val.addr +'</div></a></td>' +
    '<td><div id="des">' + val.des + '</div> </td>' +
    '<td><a><div id="viewed">' + val.viewed + '</div></a></td>' +
    '<td><a><div id="status">'+
val.status+'</div></a></td></tr>';
});

$('#items').append(output);
/************ end */

DEMO

演示

#8


1  

Try this. Its shows all data in table. http://jsfiddle.net/Navneethk/zcpp51tc/2/

试试这个。它显示了表中的所有数据。http://jsfiddle.net/Navneethk/zcpp51tc/2/

#9


1  

var html = '<tr>';
 for(var i = 0 ;i < data.length;i++){ 
  var val = data[i];
  html += '<td>'+i+'</td>'+
            '<td><a><div id="name'+id+'">'+ val.name +'</div> </a></td>'+ 
            '<td><a><div id="price'+id+'">'+ val.price +'</div> </a></td>'+ 
            '<td><a><div id"addr'+id+'">+ val.addr +</div></a></td>'+ 
            '<td><div id="des'+id+'">' +val.des+ '</div> </td>'+ 
            '<td><a><div id="viewed'+id+'">'+ val.viewed +'</div></a></td>'+ 
            '<td><a><div id="status'+id+'">' val.status '</div></a></td>';
}

 $("#items").html(html);

#10


0  

You were assigning all 5 data row to the same template so that you only see the last data set returned. You should create those 5 row dynamically by using createElement or jQuery.

您将所有5个数据行分配给同一个模板,以便只看到返回的最后一个数据集。您应该使用createElement或jQuery动态创建这5行。

#1


10  

Lots of good answers, but since I've created an example I'll post that too. If nothing else it might give you, or someone else, an alternative solution. I'm using classes instead of Id's, and keep your original structure.

有很多很好的答案,但是既然我已经创建了一个示例,我也将发布它。如果没有别的东西,它可能会给你或者其他人一个替代的解决方案。我使用的是类而不是Id,并且保持原来的结构。

Since this was accepted as answer I should also mention why your code failed:
Your each loop is continually overwriting the contents of your table row data, instead of creating new rows. Another thing that needed fixing is that you had given the columns Id's, and those cannot stay (as they were) if you want to repeat the rows, since Id's within a page must be unique.

由于这被接受为答案,我还应该提到代码失败的原因:您的每个循环不断覆盖表行数据的内容,而不是创建新的行。另一个需要修改的地方是,您已经给定了列Id,如果您想重复行,那么它们就不能停留(就像它们一样),因为Id在一个页面中必须是惟一的。

There are many methods to create new elements. I chose clone() as I figure you would always have a row for header that could easily be used to clone/copy. Also I added a unique Id attribute to each tr. These are not really used in the current implementation below, but it might be good to have as reference later in your project.

有许多方法可以创建新元素。我选择了clone(),因为我认为您总会有一个用于header的行,可以很容易地用于克隆/复制。我还为每个tr添加了一个唯一的Id属性,这些属性在下面的当前实现中并没有真正使用,但是最好在以后的项目中使用它们作为参考。

var data = [{"name":"dfasdfas","price":"0","addr":"dfasdfas","des":"sadfdfasdfasdf","viewed":"0","img":"","status"
:"1"},{"name":"Heng","price":"0","addr":" dflkas;df","des":"asdfasfasdfasdfasdfasdfasfasdfasdfasdfas"
,"viewed":"0","img":"","status":"1"},{"name":"asdDasdA","price":"0","addr":"asdADasd","des":"ASDasdASD"
,"viewed":"0","img":"","status":"1"},{"name":"asdfas","price":"0","addr":"fasdfas","des":"dfasdf","viewed"
:"0","img":"","status":"1"},{"name":"asdf","price":"0","addr":"asdfasdfas","des":"asdfasdfasdf","viewed"
:"0","img":"","status":"1"}];

//place within the Ajax success
$.each(data, function(i, val) {
  var currRow = $("#tr0").clone().appendTo($('#items')).attr('id','tr' + (i + 1));
  currRow.find('td:eq(0)').html(i + 1);
  currRow.find('.name').html(val.name);
  currRow.find('.price').html(val.price);
  currRow.find('.addr').html(val.addr);
  currRow.find('.des').html(val.des);
  currRow.find('.viewed').html(val.viewed);
  currRow.find('.status').html(val.status);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
  <tbody id="items">
    <tr id="tr0">
      <td>Id</td>
      <td><a><div class="name">Name</div></a></td>
      <td><a><div class="price">Price</div></a></td>
      <td><a><div class="addr">Addr</div></a></td>
      <td><div class="des">Des</div></td>
      <td><a><div class="viewed">Viewed</div></a></td>
      <td><a><div class="status">Status</div></a></td>
    </tr>
  </tbody>
</table>

#2


5  

You can try this, I test it locally and it works:

你可以试试这个,我在本地测试,它是有效的:

$.ajax({
    url: '<?php echo base_url('ads/select_post'); ?>',
    data: {},
    dataType: "json",
        cache: false,
        success: function (data) {
        $.each(data, function (i, val) {
            var tr = "<tr>" +
                "<td>"+ (i + 1) + "</td>" +
                "<td>"+ val.name + "</td>" +
                "<td>"+ val.price + "</td>" +
                "<td>"+ val.addr + "</td>" +
                "<td>"+ val.des + "</td>" +
                "<td>"+ val.viewed + "</td>" +
                "<td>"+ val.status + "</td>" +
                "</tr>";
            $(tr).appendTo("tbody");
        });
    }
});

And your html table:

和你的html表:

<table>
    <tbody id="items">

    </tbody>
</table>

#3


5  

You need something like this:

你需要这样的东西:

DEMO HERE

演示

HTML Structure

HTML结构

<table>
    <thead>
        <th>Sl No.</th>
        <th>Address</th>
        <th>Description</th>
        <th>Image</th>
        <th>Name</th>
        <th>Price</th>
        <th>Status</th>
        <th>Viewed</th>
    </thead>
    <tbody id="items">
    </tbody>
</table>

JS

JS

    $.each(data, function (i, val) { 
           $("tbody#items").append("<tr><td>"+(i+1)+"</td><td><a><div>"+val.addr+"</div></a></td>"
                +"<td><a><div>"+val.des+"</div></a></td>"
                +"<td><a><div>"+val.img+"</div></a></td>"
                +"<td><a><div>"+val.name+"</div></a></td>"
                +"<td><a><div>"+val.price+"</div></a></td>"
                +"<td><a><div>"+val.status+"</div></a></td>"
                +"<td><a><div>"+val.viewed+"</div></a></td></tr>");
    });

#4


5  

You need to create table rows() in the ajax success.
And you should not use same ids in the td tags.

您需要在ajax成功中创建表行()。你不应该在td标签中使用相同的id。

var html = "";
$.ajax({
  url: '<?php echo base_url('ads/select_post'); ?>',
   data: {},
   dataType: "json",
   cache: false,
   success: function (data) {
     $.each(data, function (i, val) { 
        console.log(val.name);

        html +="<tr>";
        html += "<td>" + val.name + "</td>" ;
        html += "<td>" + val.price + "</td>" ;
        html += "<td>" + val.addr + "</td>" ;
        html += "<td>" + val.des + "</td>" ;
        html += "<td>" + val.viewed + "</td>" ;
        html += "<td>" + val.status + "</td>" ;
        html +="</tr>";
    });
    $("$items").html(html);
  }
});

Your html:

html:

<table>
    <tbody id="items">

    </tbody>
</table>

#5


3  

You probably need some code like this, This is rough idea you can let me know if you don't get it

你可能需要一些像这样的代码,这是一个粗略的想法,如果你不理解,可以告诉我

this.tableElement = jQuery('<table/>', {
}).appendTo(gridWrapElement);

var tableBody = jQuery('<tbody/>', {
    'class': 'eg-table-body'
});

this.tableBodyRow = jQuery('<tr/>', {
});

var scope = this;
var columns = [{
        name:"Name",
        dataIndex:"name",
        width: "33%"
    },{
        name:"Price",
        dataIndex:"price",
        width: "33%"
    },{
        name:"Address",
        dataIndex:"addr",
        width: "34%"
    }];
$.each(this.columns, function(index, column) {
    var tableBody = jQuery('<td/>', {
        width: column.width,
        columnDataIndex: column.dataIndex,
        columnIndex: index
    });

    jQuery('<div/>', {
        html: "<a>" + column.name + "</a>",
        class: "eg-table-Body-div"
    }).appendTo(tableBody);

    tableBody.appendTo(scope.tableBodyRow);
    scope.tableBodyItems.push(tableBody);
});

jQuery(this.tableBodyRow).appendTo(tableBody);
jQuery(tableBody).appendTo(this.tableElement);

#6


3  

var body = '';
$.each(val,function(i,j){
  body = body + '<tr><td>'+i+1+'</td>';
  body = body + '<td>'+j.name+'</td>';
  body = body + '<td>'+j.price+'</td>';
  body = body + '<td>'+j.addr+'</td>';
  body = body + '<td>'+j.des+'</td>';
  body = body + '<td>'+j.viewed+'</td>';
  body = body + '<td>'+j.status+'</td></tr>';
});
$('#items').html(body);

This will give you the table with values

这将为您提供具有值的表

#7


3  

It is better if you can rows dynamically. Then append generated html into tbody table like example below :

如果可以动态地行,那就更好了。然后将生成的html添加到如下示例所示的tbody表中:

HTML

HTML

<table>
<tbody id="items">
    <tr>
        <td>No.</td>
        <td>name</td>
        <td>price</td>
        <td>addr</td>
        <td>des</td>
        <td>viewed</td>
        <td>status</td>
    </tr>
</tbody>

JS

JS

var data = [{
"name": "dfasdfas",
    "price": "0",
    "addr": "dfasdfas",
    "des": "sadfdfasdfasdf",
    "viewed": "0",
    "img": "",
    "status": "1"
}, {
"name": "asdDasdA",
    "price": "0",
    "addr": "asdADasd",
    "des": "ASDasdASD",
    "viewed": "0",
    "img": "",
    "status": "1"
}];

/************ put this inside ajax success block*/
var output;
$.each(data, function (i, val) {
output += '<tr><td>' + i + '</td>' +
    '<td><a><div id="name">' + val.name + '</div> </a></td>' +
    '<td><a><div id="price">' + val.price + '</div> </a></td>' +
    '<td><a><div id"addr">'+ val.addr +'</div></a></td>' +
    '<td><div id="des">' + val.des + '</div> </td>' +
    '<td><a><div id="viewed">' + val.viewed + '</div></a></td>' +
    '<td><a><div id="status">'+
val.status+'</div></a></td></tr>';
});

$('#items').append(output);
/************ end */

DEMO

演示

#8


1  

Try this. Its shows all data in table. http://jsfiddle.net/Navneethk/zcpp51tc/2/

试试这个。它显示了表中的所有数据。http://jsfiddle.net/Navneethk/zcpp51tc/2/

#9


1  

var html = '<tr>';
 for(var i = 0 ;i < data.length;i++){ 
  var val = data[i];
  html += '<td>'+i+'</td>'+
            '<td><a><div id="name'+id+'">'+ val.name +'</div> </a></td>'+ 
            '<td><a><div id="price'+id+'">'+ val.price +'</div> </a></td>'+ 
            '<td><a><div id"addr'+id+'">+ val.addr +</div></a></td>'+ 
            '<td><div id="des'+id+'">' +val.des+ '</div> </td>'+ 
            '<td><a><div id="viewed'+id+'">'+ val.viewed +'</div></a></td>'+ 
            '<td><a><div id="status'+id+'">' val.status '</div></a></td>';
}

 $("#items").html(html);

#10


0  

You were assigning all 5 data row to the same template so that you only see the last data set returned. You should create those 5 row dynamically by using createElement or jQuery.

您将所有5个数据行分配给同一个模板,以便只看到返回的最后一个数据集。您应该使用createElement或jQuery动态创建这5行。