【问题标题】:Create html table from array from ajax response从ajax响应的数组创建html表
【发布时间】:2019-10-05 03:40:42
【问题描述】:

在我的 Laravel 应用程序中,我添加了 ajax 查询(在按下按钮后工作)。我在 ajax 中得到结果,我在控制台上看到它(它是数组)。 但我需要将 js 的答案发送到 PHP 以创建表格

这是输入代码:

<input type="text" name="check" id="check">

这是按钮的代码:

<button type="button" class="check-client btn btn-success">Find</button>

这是ajax(JS)的代码:

$(document).on("click", ".check-client", function () {
    const data = $("#check").val();

    $.ajax({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        },
        type: 'POST',
        data: {
            'data': data
        },
        url: '/checkValues',
        success: function (result) {
            console.log(result);
            const dataForTable = result;
        }
    });
});

为了创建表,我尝试这样做:

发送响应到php+html:

$(".testClass").append(result);

得到这个值:

<div class="testClass"></div>

并使用 foreach 创建一个表:

<div class="testClass"></div>
<table class="table table-bordered text-center">
    <thead>
        <tr>
            <th scope="col">ID</th>
            <th scope="col">Person</th>
            <th scope="col">Cost</th>
        </tr>
    </thead>
    <tbody>
      @foreach($dataForTable as $item)
        <tr>
          <th scope="row">$item['id']</th>
          <td>$item['person']</td>
          <td>$item['cost']</td>
        </tr>
      @endforeach
    </tbody>
</table>

所以,它不起作用。如何从 ajax 响应创建表?

【问题讨论】:

  • 你的 ajax 响应是什么?
  • @Will, date: [{id: 1, person: 'Jack', cost: '12'}, {id: 2, person: 'Kate', cost: '15'}]

标签: javascript php html ajax laravel


【解决方案1】:

问题是您试图在客户端运行 jQuery 以在服务器端使用 ajax 请求 (dataForTable) 的返回,它超出了 PHP 上下文服务器。 PHP只在服务器端工作,而jQuery在浏览器客户端工作,如果你想在服务器端运行javascript你必须搜索其他技术,比如Node,看看node.js

如果您想在客户端使用 ajax 请求更新表,则必须在请求后更新客户端的表迭代变量 (dataForTable),如下所示:

$.getJSON( "ajax/test.json", function( data ) {
  var items = [];
  $.each( data, function( key, val ) {
    items.push( "<li id='" + key + "'>" + val + "</li>" );
  });

$( "<ul/>", {
    "class": "my-new-list",
    html: items.join( "" )
  }).appendTo( "body" );
});

jQuery中还有很多类似的例子。

最后,您必须在客户端工作,无论您想使用 jQuery,还是使用 PHP 帮助程序在服务器端工作。

【讨论】:

    猜你喜欢
    • 2015-05-03
    • 2018-11-08
    • 1970-01-01
    • 1970-01-01
    • 2015-07-22
    • 1970-01-01
    • 2012-03-21
    • 2014-08-02
    • 1970-01-01
    相关资源
    最近更新 更多