2010-09-06 40 views
2

我想在网页中模拟CLI,其中用户键入页面上的命令并将其发送到服务器以供执行,并显示响应在页面中 - 非常像CLI行为。使用jQuery模拟网页中的CLI

我的jQuery fu不是它应该是什么,我认为这必须是一个'模式',必须经常发生,所以也许有人可以指向某个地方有类似代码的资源,或者有人可以让我以张贴在这里的片段开始。

这是我第一次刺伤它。更正,改进欢迎。

<html> 
    <head> 
    <title>Simple CLI</title> 
    <script src="jquery.js"> 
    </head> 
    <body> 
    <div> 
     <div id="console"> 
     </div> 
     <!-- Is having an input tag without an enclosing form tag valid (X)HTML? --> 
     <input id="cmd_input" type="text" name="cli_cmd" /> 
    <div 
    <script type="text/javascript"> 
    /* [CDATA[ */ 
    $(document).ready(function(){ 
     $.post('url': "example.php", {'cmd': $('#cmd_input').val()}, 
      function(data){ $('#cmd_input').append(data.resp); }, 
      'type': 'json'); 
    }); 
    /* ]]> */ 
    </script> 
    </body> 
</html> 
+1

相关http://uni.xkcd.com/ – NullUserException 2010-09-06 21:13:49

+0

酷!这正是我想要做的... – morpheous 2010-09-06 21:15:53

回答

0

这应该Ajax请求上<enter>

<html> 
    <head> 
    <title>Simple CLI</title> 
    <script src="jquery.js"> 
    </head> 
    <body> 
    <div> 
     <div id="out"></div> 
     <input id="in" type="text" /> 
    </div> 
    <script type="text/javascript"> 
     $('#in').keyup(function(e) { 
     if (e.which !== 13) 
      return; 
     var cmd = { cmd: $(this).val() }; 
     $(this).val(''); 
     $.post('example.php', cmd, function(data) { 
      $('#out').append(data); 
     }); 
     }; 
    </script> 
    </body> 
</html> 
0
<html> 
    <head> 
    <title>Simple CLI</title> 
    <script src="jquery.js"> 
    <style> 
     ​#container_command { 
     background-color:#000000; 
     color:#ffffff; 
     font-family:Courier New; 
     }​ 
    <style> 
    </head> 
    <body> 
    <div> 
     <div id="container_command"> 
      <code id="console"></code> 
      <br /> 
      &#35; command &gt;<input id="cmd_input" type="text" />&nbsp; 
     </div> 
    </div> 
    <script type="text/javascript"> 

    /* [CDATA[ */ 
    $(function() { 

     $('#cmd_input').keypress(function(ev) { 

     if (ev.keyCode == "13") 
      ev.preventDefault(); 
     else 
      return true; 

     var command = $('#cmd_input').val(); 

     if (command.length == 0) 
      return true; 

     $('#cmd_input').val(""); 

     $.post("example.php", {'cmd': command}, 
      function(data) 
      { 
       var console_response = data.resp..replace(/\n/, '<br />'); 
       $("#console").append(command + ": <br />" +console_response+"<br />"); 
      } 
     ,"json"); 

     }); 

    }); 
    /* ]]> */ 

    </script> 
    </body> 
</html>