Ajax异步更新网页(使用jQuery)

Posted yehuan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Ajax异步更新网页(使用jQuery)相关的知识,希望对你有一定的参考价值。

一、页面代码

<!DOCTYPE html>
<html>
<head>
<title>MyHtml.html</title>

<meta name="keywords" content="keyword1,keyword2,keyword3">
<meta name="description" content="this is my page">
<meta name="content-type" content="text/html; charset=UTF-8">

<body>
    <table>
        <tr>
            <td>Login:</td>
            <td><input id="username" type="text" name="login"></td>
        </tr>
        <tr>
            <td>Password:</td>
            <td><input type="password" name="password" id="password"></td>
        </tr>
        <tr>
            <td colspan="2"><input type="submit"></td>
        </tr>
    </table>
</body>
</html>

 

二、jQuery代码

// 导入jQuery
<script type="text/javascript" src="../js/jquery-1.8.3.min.js"></script> <script type="text/javascript"> $(document).ready(function() $("#username").keyup(function() var value = $(this).val(); var strData = "username=" + value; $.ajax( url : "MyServlet1", type : "get", //data : "username":value, // json格式 data: strData, dataType : "text", success : function(data, strStatus, xhr) if (data == "已使用") $("#username").css("border-color", "red"); else $("#username").css("border-color", "green"); , error : function(xhr, strStatus, strError) alert(strError); ); ); ); </script>

 

三、servlet代码

package com.yh.myServlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MyServlet1 extends HttpServlet 

    private static final long serialVersionUID = 1L;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
        // TODO Auto-generated method stub
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        String userName = request.getParameter("username");
        System.out.println(userName);
        if (userName.equals("yh")) 
            out.print("已使用");
         else 
            out.print("可使用");
        
    

 

四、配置servlet

  <servlet>
      <servlet-name>MyServlet1</servlet-name>
      <servlet-class>com.yh.myServlet.MyServlet1</servlet-class>
  </servlet>
  
  <servlet-mapping>
      <servlet-name>MyServlet1</servlet-name>
      <url-pattern>/Pages/MyServlet1</url-pattern>
  </servlet-mapping>

注:这个Pages是根据html页面的路径设置的

以上是关于Ajax异步更新网页(使用jQuery)的主要内容,如果未能解决你的问题,请参考以下文章

ajax交互方法实现

JQuery快速入门-Ajax

Ajax - 异步原理及Js/Jquery两种使用方式

JQuery中ajax使用方法

jQuery ajax 异步请求

JS-AJAX and jQuery-AJAX