[英]JSON data not displaying using .html()
在發布此問題之前,我確實在這里搜索並獲得了不同的答案,我認為這不符合我的需求。 單擊時有一個按鈕,將運行以下js腳本
$("#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()放入容器時,什么也沒發生。 這里的罪魁禍首是什么? 我正在對其他功能進行此編碼,但僅此部分不起作用
代碼:
<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
var data = $.parseJSON(data);
成功添加此功能。 希望對您有所幫助!
從您的示例中,我想您不需要將數據解析為json。 只需回顯$results
並綁定ajax成功
$("#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;
在echo json_encode之前添加以下行:
header('Content-Type: application/json');
echo json_encode($data);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.