AJAX在JQuery中的应用详解

2020-05-17 06:23:48易采站长站整理

AJAX在jQuery中的应用

1. $.ajax()方法

$.ajax()方法是一个功能十分强悍的一个底层方法,基于该方法实现的$.get()和$.post()都是常用的向服务器请求数据的方法。

1.1 $.ajax()中的参数及使用方法

$.ajax()调用的语法格式为:

$.ajax([options])

其中,可选参数[options]作为$.ajax()方法中的请求设置,其格式为key/value,既包含发送请求的参数,也含有服务器响应回调的数据,常用的参数具体格式如下:

1.2 $.ajax()方法的使用实例

实例中使用的是一个简单的基于SSH框架的Java Web项目

这里我们通过一个controller来接受一个UserEntity类型的数据,然后返回一个Map类型的数据,实现页面的请求。


@Controller
@RequestMapping("/user")
public class UserController {
@Resource
private IUserService userService;
@ResponseBody
@RequestMapping(value="/login", method = RequestMethod.POST)
public Map<String,Object> login(UserEntity user){
Map<String,Object> map = new HashMap<String,Object>();
System.out.println(user.toString());
//判断数据库中是否存在这样一个UserEntity数据
boolean loginResult = userService.isExist(user);
map.put("loginResult", loginResult);
return map;
}
}

前端代码:


<%@ 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%>" rel="external nofollow" >
<title>用户登录</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="<%=basePath %>css/bootstrap.css" rel="external nofollow" >
</head>
<body>
<div>
<div class="input-group">
<span class="input-group-addon" id="name_span">UserName</span>
<!--从这里输入一个username-->
<input name="username" type="text" class="form-control" placeholder="UserName" aria-describedby="name_span">
</div>
<div class="input-group">