如何使用ajax

时间:2017-09-19 06:47:33

标签: javascript html css

我能够将从ajax调用返回的数据显示为警报,但是我想使用ejs以表格格式显示它。

有人可以帮忙吗?

AJAX致电

$('#submit').on('click', function() {
  $.ajax({
    url: '/render',
    type: 'get',
    dataType: 'json',
    success: function(data) {

      for (var i = 0; i < data.length; i++) {
        alert(data[i].item);
      }
    }
  });
});

HTML

<div class="container">

  <div class="row">
    <div class="col-md-4">
      <label style="margin-left: 20px;">Shopping item</label>&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;
      <label>Quantity</label>
    </div>
  </div>
  <div class="row">
    <div class="col-md-8">
      <input type="text" id="item" name="item" />&emsp;&emsp;&emsp;&emsp;
      <input type="text" id="quan" name="quan" />&emsp;&emsp;&emsp;&emsp;
      <input type="submit" id="submit" value="Add item" style="background-color: #a3a3c2; color:white; width:170px;" />
    </div>
  </div>

  <div class="row">
    <div class="col-md-8">
      <table>
        <thead>
          <th>Item</th>
          <th>Quantity</th>
        </thead>
        <tbody id="tbody">

        </tbody>
      </table>
    </div>
  </div>
  </form>

2 个答案:

答案 0 :(得分:2)

试试这个

$('#submit').on('click',function() {
    $.ajax({
        url: '/render',
        type: 'get',
        dataType: 'json',
        success: function(data) {

           for(var i=0;i<data.length;i++)
           {
             var Html="<tr>
                <td>"+data[i].item+"</td>
                <td>"+data[i].Quantity+"</td>
            </tr>";
            $('#tbody').append(Html);

           }
        }
        });
    });

答案 1 :(得分:1)

我不完全确定你想要实现的目标。 但是如果你想使用ejs,那么你应该创建一个ejs模板来传递数据。

获取您的数据并使用它调用模板;

$('#submit').on('click',function() {
    $.ajax({
        url: 'data.json',
        type: 'get',
        dataType: 'json',
        success: function(data) {

           var result = new EJS({url: 'productstemplate.ejs'}).render({products:data}); 
           document.getElementById('product_list').innerHTML = result
        }
        });
    });

我制作了一个ajax请求的工作示例,它使用ejs进行渲染 plunkr sample,也许这可以帮助你