我正在爲我的服務器管理應用程序編寫一個模擬終端網頁。基本上,使用jquery,ajax和php的shell_exec(),我正在模擬一個終端。無法在一次頁面加載中通過兩次提交相同的表單(通過jQuery和AJAX)
終端的輸入行基本上只是一個包裝在窗體中的input
元素。有一個jquery處理程序在表單提交時觸發ajax請求(按下Enter鍵)。
當我第一次提交時(當我發送第一個命令時),一切正常。但是,一旦我嘗試發送第二個頁面,頁面一直滾動到頂部,並且表單未提交。
這裏是jQuery的:
$("#terminal-form").unbind('submit').submit(function() {
var current_dir = $("#path").text();
var command = $("#terminal-input").val();
$.ajax({
url: "terminal.php",
type: "post",
data: { current_dir: current_dir, command: command },
dataType: 'json',
success: function(data) {
$("#terminal table").remove();
$("#terminal").append("[email protected]:" + current_dir + " $ " + command + "<br>");
if (data['output'] != '') {
$("#terminal").append(data['output'] + "<br>");
}
$("#terminal").append("<table class='terminal-content'><tr><td nowrap='nowrap' style='overflow:auto;whitespace:nowrap'>[email protected]:" + data['wd'] + "$<td style='width:99%'><form style='margin:0px;padding:0px' id='terminal-form'><input id='terminal-input' type='text'></input></form></td></tr></table>");
$("#terminal-input").focus();
}
})
return false;
})
的success
處理器基本上只是刪除舊錶,並插入明文的結果,本質上給人的錯覺,這一切都互動。
這裏的PHP後端:
<?php
$current_dir = $_POST['current_dir']; // get current directory
$command = $_POST['command']; // get the command to run
chdir($current_dir); // change into the right directory
if (substr($command, 0, 2) == "cd") {
chdir(substr($command, 3));
$output = "";
} else {
$output = shell_exec($command); // get the command's output
}
$wd = shell_exec('pwd'); // get the current working directory
$result = array('wd' => $wd, 'output' => $output); // create array
$result = json_encode($result); // convert to json for jquery
echo $result;
問題是,當我去提交第二份命令。我甚至不認爲表單被正確提交。我做了一些googleing,發現你需要解除綁定處理程序,我正在做,但它仍然無法正常工作。
您可以在替換較少的DOM時完成同樣的操作。刪除整個'