2017-05-20 39 views
0

我一直在嘗試從我的服務器傳回一個JSON對象中的HTML,我最終設法使其工作。從包含的php文件返回JSON格式的HTML

我現在希望能夠從包括文件中傳回HTML,但無法解決如何做到這一點....是否有可能?

我的index.html是這樣的:

<head> 
<script src="ajax.js"></script> 
</head> 
<body> 
<div class="main-content"> 
<p>Some content to be replaced</p> 
</div> 
</body> 

我的JavaScript調用Ajax如下:

$.ajax({ 
    type: 'POST', 
    dataType: 'json', 
    url: 'http://example.com/process.php', 
    data: formData, 
    success: function(rtnData) { 
    $('.main-content').replaceWith(rtnData['html']); // Redraw content 
    }, 
    error: function(rtnError) { 
    console.log('there was a problem'); 
    } 
}); 

我process.php文件是在這裏:

<?php 
$returnVal['html'] = include 'test.php'; 
echo json_encode($returnVal); 

而且最後,我的test.php文件是:

<div class="main-content"> 
    <div id="content"> 
    <p>The simple sum 5 + 4 = <?php echo 5 + 4;?></p> 
    </div> 
</div> 

運行時,它在rtnData['html']中什麼也沒有返回,我看到控制檯日誌'有問題'。

如果我改變$returnVal['html'] = include 'test.php';file_get_contents('test.php');它返回的HTML,但PHP返回爲文本,而不執行的,所以我的HTML被替換爲The simple sum 5 + 4 = <?php echo 5 + 4;?>,而不是The simple sum 5 + 4 = 9

是我想要實現的可能嗎?我需要離開test.php作爲外部文件;不幸的是,我無法改變這一點。

回答

0

一種可能的方式是:您忘記了dataType: json並從您的process.php返回純HTML。

process.php內容將只是:

<?php 
include 'test.php'; 

阿賈克斯成功將是:

success: function(rtnData) { 
    $('.main-content').replaceWith(rtnData); // Redraw content 
} 

如果您仍然需要返回JSON - 您test.php必須buffer output

內容process.php將是:

<?php 
ob_start(); 
include 'test.php'; 
$returnVal['html'] = ob_get_clean(); 
echo json_encode($returnVal); 

在這種情況下,Ajax成功保持不變。

+0

感謝百萬u_muider ....我會試一試,儘快接受你的答案。關於只傳回HTML而不是JSON,如果我這樣做,傳回錯誤的最佳方法是什麼?我會發送一個500內部服務器錯誤標題以及一些HTML還是有點破解? – Damian

+0

爲什麼不行,但在500狀態的情況下,'error'處理程序將在ajax中調用,而不是'success'。 –

+0

再次感謝您的回答,祝您工作愉快! – Damian