zoukankan      html  css  js  c++  java
  • AJAX异步实现

    AJAX 最大的优点是在不重新加载整个页面的情况下,可以与服务器交换数据并更新部分网页内容。

    <head>
    <meta charset="utf-8">
    <script>
    function showHint(str)
    {
      var xmlhttp;
      if (str.length==0)
      { 
        document.getElementById("txtHint").innerHTML="";
        return;
      }
      if (window.XMLHttpRequest)
      {
        // IE7+, Firefox, Chrome, Opera, Safari 浏览器执行代码
        xmlhttp=new XMLHttpRequest();
      }
      else
      {
        // 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","/try/ajax/gethint.php?q="+str,true);
      xmlhttp.send();
    }
    </script>
    </head>
    <body>
    
    <h3>在输入框中尝试输入字母 a:</h3>
    <form action=""> 
    输入姓名: <input type="text" id="txt1" onkeyup="showHint(this.value)" />
    </form>
    <p>提示信息: <span id="txtHint"></span></p> 

    如果输入框不为空,showHint() 函数执行以下任务:

    • 创建 XMLHttpRequest 对象
    • 当服务器响应就绪时执行函数
    • 把请求发送到服务器上的文件
    • 请注意我们向 URL 添加了一个参数 q (带有输入框的内容)

       gethint.php:

    <?php
    // Fill up array with names
    $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[]="Tove";$a[]="Unni";
    $a[]="Violet";
    $a[]="Liza";
    $a[]="Elizabeth";
    $a[]="Ellen";
    $a[]="Wenche";
    $a[]="Vicky";
    //get the q parameter from URL
    $q=$_GET["q"];
    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];
          }
        }
      }
    }
    if ($hint == "")
    {
      $response="no suggestion";
    }
    else
    {
      $response=$hint;
    }
    
    //output the response
    echo $response;
    ?>
  • 相关阅读:
    python-day49--前端 css-层叠样式表
    python-day49--前端 html
    python-day48--mysql之视图、触发器、事务、存储过程、函数
    python-day47--pymysql模块
    python-day47--mysql数据备份与恢复
    python-day46--前端基础之html
    python-day45--mysql索引
    window系统下远程部署Tomcat
    tomcat下部署应用helloworld
    tomcat配置文件context.xml和server.xml分析
  • 原文地址:https://www.cnblogs.com/soyo/p/6887906.html
Copyright © 2011-2022 走看看