开发者

Mimicking a CLI in a web page, using jQuery

I want to mimic a CLI in a web page, where a user types in a command on the page, and it is sent to the server for execution, and the response is displayed in the page - much like a CLI behavior.

My jQuery fu is not what it should be and I am thinking that this must be a 'pattern' that must occur quite often so maybe someone can point to a resource somewhere that has similar code, or maybe someone can get me started with a snippet posted in here.

Here is my first sta开发者_StackOverflowb at it. Corrections, improvements welcome.

<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>


This should ajax request on <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>


<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>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜