javascript - jQuery 在模态中给出未定义的值

标签 javascript php jquery html

我想将数据从数据库显示到模式表中,我已经尝试过这段代码。但是,它一直给出未定义的值

这是图片:

enter image description here

模态代码:

<div id="myModal" class="modal fade" tabindex="-1" role="dialog">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title">Modal title</h4>
      </div>
      <div class="modal-body">
          <form id="myForm" action="" method="post" class="form-horizontal">
            <table class="table table-bordered table-striped">
              <thead>
              <tr>
                <th>NIK</th>
                <th>Nama</th>
              </tr>
              </thead>
              <tbody id="TampilDataModal">
              </tbody>
            </table>
          </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>

脚本:

$('#TampilData').on('click','.item-detail-plp', function(){
  var idPelapor = $(this).attr('data');
  $('#myModal').modal('show');
  $.ajax({
      url: 'GetPelapor',
      async: false,
      method: 'get',
      type: 'ajax',
      data: {idPelapor:idPelapor},
      datatype: 'json',
      success: function (data) {
      var html = '';
      var i;
      for(i=0; i<data.length; i++){
        html +='<tr>'+
              '<td>'+data[i].idPelapor+'</td>'+
              '<td>'+data[i].nama+'</td>'+
              '</tr>';
      }
      $('#TampilDataModal').html(html);   
    }
    });
});

来自 json 的响应 [{"idPelapor":"3","nama":"a"}]

最佳答案

您需要将 JSON 转换为对象文字,否则它将循环遍历 JSON 字符串的每个字符并尝试获取每个字符的未定义属性。

function (data) {
    data = JSON.parse(data);`

关于javascript - jQuery 在模态中给出未定义的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44469540/

相关文章:

javascript - 如何在 JSX 中打印 props 对象,我收到 TypeError : Cannot read property of undefined

javascript - 打开嵌套导航器的父级

javascript - jQuery:在代码中两次/稍后添加属性?

javascript - 在 jQuery 中使用页面 Url

javascript - 尝试获取 JSONP 但 JS 认为我指向其他 JS 文件

php - 检查一个类是否是另一个类的子类

php - 复合模式和依赖注入(inject)

PHP 类扩展了 Singleton 模式

jquery - 向上滑动输入框

javascript - Ajax 加载内容,jquery 效果不起作用