2017-06-23 62 views
0

在发布这个问题之前,我在这里搜索并得到了不同的答案,我认为它不符合我的需要。我有一个按钮,点击后,下面的JS脚本运行使用.html()不显示JSON数据()

$("#update-details-btn").on('click', function() { 
     $.ajax({ 
      type: 'post', 
      dataType: 'json', 
      data: "confirmation="+get_data, 
      url: '../for_update_details', 
      success: function(data) 
      { 
       console.log(data); 
       $('div#update_details_body').html(data.results); 

,这是容器

<div id="update_details_body" class="modal-body"></div> 

数据来自一个PHP函数

$data['results'] = NULL; 
$results = "<div class='form-group'>"; 
$results .= "<label for='document-type' class='col-sm-4 control-label'>Category</label>"; 
$results .= "</div>"; 
$data['results'] = $results; 
echo json_encode($data); 

正如你所看到的从js中,我做了一个console.log,它打印出data.results包含的内容,但是当我使用.html()放入容器内时,什么都不会发生。这里可能是什么罪魁祸首?我正在做这个编码到其他功能,但只有这个部分不工作

+0

可能你需要'console.log'之前的'JSON.parse(data)'。 – 31piy

+0

不需要解析他有'dataType:'json',' – guradio

+0

你确定数据没有绑定到你的div,我认为这个问题是class =“modal-body”隐藏在某处 – Rahul

回答

1

代码:

<html> 
<head> 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> 
<script type="text/javascript"> 
$(document).ready(function(){ 
    $("#update-details-btn").on('click', function() { 
     alert("inside"); 
     $.ajax({ 
      type: 'post', 
      dataType: 'json', 
      url: 'php_file.php', 
      success: function(data) 
      { 
       console.log(data); 
       $('div#update_details_body').html(data.results); 
      } 
     }); 
    }); 
}); 
</script> 
</head> 
<style> 
.modal-body 
{ 
    margin: 0px; 
    padding: 0px; 
    width: 100px; 
    height: 100px; 
} 
</style> 
<body> 
<div id="update_details_body" class="modal-body"></div> 
<input type="button" id="update-details-btn" name="button" value="button"> 
</body> 
</html> 

PHP代码不是chnage

0
var data = $.parseJSON(data); 

添加此功能成功功能。希望它有帮助!

+0

不需要解析他有'dataType:'json',' – guradio

0

从你的例子我叮叮当当,你不需要解析数据到json中。简单地echo $results和绑定在阿贾克斯成功

$("#update-details-btn").on('click', function() { 
     $.ajax({ 
      type: 'post', 

      data: "confirmation="+get_data, 
      url: '../for_update_details', 
      success: function(data) 
      { 
       console.log(data); 
       $('div#update_details_body').html(data); 

PHP:

$data['results'] = NULL; 
$results = "<div class='form-group'>"; 
$results .= "<label for='document-type' class='col-sm-4 control-label'>Category</label>"; 
$results .= "</div>"; 
echo $results; 
+0

嗨,我会试试这个 –

0

回声json_encode之前添加以下行:

header('Content-Type: application/json'); 
echo json_encode($data);