2012-12-29 59 views
0

我正在爲我的服務器管理應用程序編寫一個模擬終端網頁。基本上,使用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,發現你需要解除綁定處理程序,我正在做,但它仍然無法正常工作。

+0

您可以在替換較少的DOM時完成同樣的操作。刪除整個'

',添加一個新表單,並重新綁定事件處理程序是相當昂貴的。 – meagar

回答

4

只要您替換元素,即使您使用完全相同的html進行替換,它也會丟失它的事件處理程序。你們看到的是形式提交的默認瀏覽器的方法,這是造成頁面重載

要解決這個問題,你可以委託提交處理程序,以便它會爲未來的形式工作,還裝載

$(document).on('submit', "#terminal-form",function() { 
    /* handler code*/ 
}) 

這將將處理程序綁定到始終存在的document,並且僅針對特定表單的ID。不會干擾頁面

中的任何其他窗體提交處理程序
+0

很酷,這工作完美,謝謝你的解釋。我沒有進入處理程序,但阿賈克斯似乎搞亂了。 – n0pe

+0

使用瀏覽器控制檯檢查AJAX請求以幫助排除故障。可以看到狀態,發送和接收的數據等 – charlietfl

+0

對,我忘了那個。乾杯。 – n0pe