我一直在嘗試從我的服務器傳回一個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作爲外部文件;不幸的是,我無法改變這一點。
感謝百萬u_muider ....我會試一試,儘快接受你的答案。關於只傳回HTML而不是JSON,如果我這樣做,傳回錯誤的最佳方法是什麼?我會發送一個500內部服務器錯誤標題以及一些HTML還是有點破解? – Damian
爲什麼不行,但在500狀態的情況下,'error'處理程序將在ajax中調用,而不是'success'。 –
再次感謝您的回答,祝您工作愉快! – Damian