JavaScript学习笔记8-jQuery异步调用方式

本文介绍了一个使用JSP作为前端页面和Servlet作为后端逻辑的简单示例,展示了如何通过AJAX请求从服务器获取数据并进行处理。包括HTML模板、CSS样式、JavaScript操作以及Servlet处理请求的详细过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前台JSP:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
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="scripts/jquery-1.4.4.js"></script>
	
	<script type="text/javascript">
	
	$(function()
	{
		$("#button1").click(function()
		{
			$.ajax({  //参数是一个对象,该对象有type url等属性
				
				type: "POST",
				url: "MyServlet",
				dateType: "html",
				data: {'param1': $("#param1").val(), 'param2': $("#param2").val()},
				success: function(returnedData){
					$("#result").val(returnedData);
				}
				
			});
		});
	});
	
	</script>
  </head>
  
  <body>
    
    <input type="text" id="param1">+
    <input type="text" id="param2">=
    
    <input type="text" id="result"> <input type="button" value="get content from server" id="button1">
     
  </body>
</html>

后台Servlet:

package com.shengsiyuan.servlet;


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 MyServlet extends HttpServlet
{
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException
	{
		int param1 = Integer.parseInt(req.getParameter("param1"));
		int param2 = Integer.parseInt(req.getParameter("param2"));
		
		resp.setHeader("pragma", "no-cache");
		resp.setHeader("cache-control", "no-cache");

		PrintWriter out = resp.getWriter();
		
		out.println(String.valueOf(param1 + param2));
		
		out.flush();
	}
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException
	{
		this.doPost(req, resp);
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值