2017-06-23 61 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);