我已經看到有關此問題的問題和解答。例如How to return a HTML file as the response to a POST request?但我在實施解決方案時遇到問題。下面是一個名爲websiteIssue的目錄中的一些php代碼示例,它不起作用,我不知道爲什麼。作爲對POST請求的響應的HTML文件?
的index.php
<?php
if(isset($_POST['page']))
{
$page = $_POST['page'];
}
else
{
$page = "";
}
include 'case.php';
?>
case.php
<?php
$testLog = 'testLog.txt';
$fileHandle = fopen('testLog.txt', 'a');
fwrite($fileHandle, '$page = '.$page."\n";
switch($page)
{
case "screen2":
include 'screen2.php';
fwrite($fileHandle, 'including screen2.php'."\n");
break;
default:
include 'screen1.php';
fwrite($fileHandle, 'including screen1.php'."\n");
break;
}
fclose($fileHandle);
?>
screen1.php
<!DOCTYPE html>
<html lang="en">
<head>
<title>screen1.php</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
</head>
<body>
<button type="button" onClick=dataSubmit({page:"screen2"})> Screen 1 => Screen2</button>
<script>
function dataSubmit(data)
{
var xmlRequest = new XMLHttpRequest();
var formData= new FormData();
for(name in data)
{
formData.append(name, data[name]);
}
xmlRequest.open('POST', 'http://localhost/websiteIssue/');
xmlRequest.send(formData);
}
</script>
</body>
</html>
screen2.php
<!DOCTYPE html>
<html lang="en">
<head>
<title>screen2.php</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
</head>
<body>
<button type="button" onClick=dataSubmit({page:"screen1"})> Screen 2 => Screen1</button>
<script>
function dataSubmit(data)
{
var xmlRequest = new XMLHttpRequest();
var formData= new FormData();
for(name in data)
{
formData.append(name, data[name]);
}
xmlRequest.open('POST', 'http://localhost/websiteIssue/');
xmlRequest.send(formData);
}
</script>
</body>
</html>
在初始加載時,它按照我的預期工作,screen1.php中的html顯示在瀏覽器中,但是當按下頁面上的按鈕時,html保持不變,而不是在screen2.php中更改爲0122輸出到testText.log是一樣的東西:
$page =
including screen1.php
$page = screen2
including screen2.php
如同可能是顯而易見的,我是一個新手到這一點,並希望有一些基本的東西我沒有做過。我使用的瀏覽器是Firefox。任何幫助將非常感激。小提示:我爲這篇文章手工重寫了代碼,並沒有運行它(運行web服務器的機器沒有連接到互聯網),希望沒有語法錯誤,但我可能犯了一個錯字某處。
感謝您的迴應:)我添加了您建議的代碼(與()後面的單詞函數),但發現我得到了xmlRequest.status的404和xmlRequest.responseText是html
對不起,這是因爲我犯了一個錯誤(我在case.php中的代碼略有不同)。你的建議工作正常我只是在函數後面添加了括號()(只是提醒別人想要嘗試),並將case中的includes改爲打印。只需要爲$頁面添加適當的代碼到屏幕上的php文件。 – Glenn