zoukankan      html  css  js  c++  java
  • 简单的Ajax应用实例

    从网页前端输入提示范围内的字符,然后显示从后台返回的结果

    <html>
    <head>
    <meta http-equiv="content-type" content="text/html;charset=utf-8">
    <script type="text/javascript">
    function showHint(str)
    {
    var xmlhttp;
    if (str.length==0)
      { 
      document.getElementById("txtHint").innerHTML="";
      return;
      }
    if (window.XMLHttpRequest)
      {// code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp=new XMLHttpRequest();
      }
    else
      {// code for IE6, IE5
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
    xmlhttp.onreadystatechange=function()
      {
      if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
        document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
        }
      }
    xmlhttp.open("GET","ajax.php?q="+str,true);
    xmlhttp.send();
    }
    </script>
    </head>
    <body>
    
    <h3>请在以下的输入框中键入字母(A - Z):</h3>
    <form action=""> 
    姓氏:<input type="text" id="txt1" onkeyup="showHint(this.value)" />
    </form>
    <p>建议:<span id="txtHint"></span></p> 
    
    </body>
    </html>

    假设输入框为空 (str.length==0),则该函数清空 txtHint 占位符的内容,并退出函数。

    假设输入框不为空,showHint() 函数运行下面任务:

    • 创建 XMLHttpRequest 对象
    • 当server响应就绪时运行函数
    • 把请求发送到server上的文件
    • 请注意我们向 URL 加入�了一个參数 q (带有输入框的内容)
    php:

    <?php
    // 用名字来填充数组
    $a[]="Anna";
    $a[]="Brittany";
    $a[]="Cinderella";
    $a[]="Diana";
    $a[]="Eva";
    $a[]="Fiona";
    $a[]="Gunda";
    $a[]="Hege";
    $a[]="Inga";
    $a[]="Johanna";
    $a[]="Kitty";
    $a[]="Linda";
    $a[]="Nina";
    $a[]="Ophelia";
    $a[]="Petunia";
    $a[]="Amanda";
    $a[]="Raquel";
    $a[]="Cindy";
    $a[]="Doris";
    $a[]="Eve";
    $a[]="Evita";
    $a[]="Sunniva";
    $a[]="Tove";
    $a[]="Unni";
    $a[]="Violet";
    $a[]="Liza";
    $a[]="Elizabeth";
    $a[]="Ellen";
    $a[]="Wenche";
    $a[]="Vicky";
    
    //获得来自 URL 的 q 參数
    $q=$_GET["q"];
    
    //假设 q 大于 0,则查找数组中的全部提示
    if (strlen($q) > 0)
      {
      $hint="";
      for($i=0; $i<count($a); $i++)
        {
        if (strtolower($q)==strtolower(substr($a[$i],0,strlen($q))))
          {
          if ($hint=="")
            {
            $hint=$a[$i];
            }
          else
            {
            $hint=$hint." , ".$a[$i];
            }
          }
        }
      }
    
    // 假设未找到提示,则把输出设置为 "no suggestion"
    // 否则设置为正确的值
    if ($hint == "")
      {
      $response="no suggestion";
      }
    else
      {
      $response=$hint;
      }
    
    //输出响应
    echo $response;
    ?>

    效果


    打包下载

  • 相关阅读:
    js键盘事件以及键盘事件拦截
    GO-&获取地址与*解引用
    Go-map
    第22课
    第21课
    第20课
    基于spring+quartz的分布式定时任务框架
    DeepLearning (三) 预处理:主成分分析与白化
    白化whitening
    如何使用RestTemplate访问restful服务
  • 原文地址:https://www.cnblogs.com/hrhguanli/p/3957402.html
Copyright © 2011-2022 走看看