当前位置: 代码迷 >> Web前端 >> 从头开始学习JAVA 6-引来JQuery
  详细解决方案

从头开始学习JAVA 6-引来JQuery

热度:251   发布时间:2013-03-10 09:38:39.0
从头开始学习JAVA 6--引入JQuery

5 JQuery

Index.jsp中,使用到JQuery

1)添加taglib

在页面头部添加如下代码:

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

Taglib类似于自定义控件。

2)添加Jquery

 

    <script type="text/javascript" src="<c:url value="/resources/jquery-1.7.2.min.js" />"></script>

<script type="text/javascript" src="<c:url value="/resources/json.min.js" />"></script>

其中,<c:url value="/resources/json.min.js" />taglib的应用。

运行后生成的代码为:

<script type="text/javascript" src="/IVSMWebDemo/resources/jquery-1.7.2.min.js"></script>

<script type="text/javascript" src="/IVSMWebDemo/resources/json.min.js"></script>

在页面中,添加一个按钮:

3)添加javascript脚本

添加页面加载完成后的函数,window.onload

$(function(){

    $("#butClick").bind('click',function(){

        alert("button clicked");

    });

  });

4)添加ajax处理

添加一个按钮,在初始化时设置该按钮click事件,代码如下:

  $(function(){

    $("#butClick").bind('click',function(){

    alert("button clicked");

    });

    $("#butAjax").bind('click',function(){

    login() ;

    });

  });

 

  function login() {

    $.post("MyTest/getId", "admin", function(sid){

       alert(sid);

    });

};

$.post("MyTest/getId", "admin", function(sid){ ”为ajax调用代码。

第一个参数是请求的路径,第二个参数是请求的参数,function(sid)为回调函数

5)页面代码

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<%

String path = request.getContextPath();

String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

%>

 

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

  <head>

    <base href="<%=basePath%>">

   

    <title>My JSP 'Index.jsp' starting page</title>

   

    <meta http-equiv="pragma" content="no-cache">

    <meta http-equiv="cache-control" content="no-cache">

    <meta http-equiv="expires" content="0">   

    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">

    <meta http-equiv="description" content="This is my page">

    <!--

    <link rel="stylesheet" type="text/css" href="styles.css">

    -->

    <script type="text/javascript" src="<c:url value="/resources/jquery-1.7.2.min.js" />"></script>

    <script type="text/javascript" src="<c:url value="/resources/json.min.js" />"></script>

 

  </head>

 

  <body>

    This is my JSP page. <br>

    <input type="button" id="butClick" value="click"/>

  </body>

  <script type="text/javascript">

  $(function(){

    $("#butClick").bind('click',function(){

    alert("button clicked");

    });

    $("#butAjax").bind('click',function(){

    login() ;

    });

  });

 

  function login() {

    $.post("MyTest/getId", "admin", function(sid){

       alert(sid);

    });

};

 

  </script>

</html>

 

6)运行效果

 

 

  相关解决方案