SpringMVC框架下,通过jQuery发送ajax异步(asynchronous)请求
java是一种可以撰写跨平台应用软件的面向对象的程序设计语言,是由Sun Microsystems公司于1995年5月推出的Java程序设计语言和Java平台(即JavaEE, JavaME, JavaSE)的总称。本站提供基于Java框架struts,spring,hibernate等的桌面应用、web交互及移动终端的开发技巧与资料
保持永久学习的心态,将成就一个优秀的你,来 继续搞起java知识。
一,如何在项目中引用jQuery
jQuery官方CDN
<span style="font-size:14px;"><script type="text/javascript" src="http://code.<a href="http://www.cfei.net/archives/tag/jquery" title="浏览关于“jquery”的文章" target="_blank" class="tag_link">jquery</a>.com/jquery-1.12.0.min.js"></script> <script type="text/javascript" src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script></span>
Google CDN(由于谷歌的网站在大陆访问受限,可能会影响加载速度)
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> <script type="text/javascript" src="http://jquery-json.googlecode.com/files/jquery.json-2.2.min.js"></script>
二,发送ajax请求,简单的demo,已经测试通过
1,JavaScript代码
//使用jQuery + Ajax + <a href="http://www.cfei.net/archives/tag/spring" title="浏览关于“Spring”的文章" target="_blank" class="tag_link">Spring</a>MVC
$(function(){
//文本框点击事件
$("#input_url").click(
function(){
//
var $a = $(this);
//发送ajax请求
$.ajax({
//
url:"AjaxAsynchronousRequestTest.action",
type:&#39;post&#39;,
data:&#39;name=admin&#39;,
dataType:&#39;json&#39;,
success:function(data,status){
if(status == "success"){
//接收服务器端传来的数据
var str_from_server = data.message;
//将接收到的数据显示到文本框
$("#response_div").html(str_from_server);
}
},
//
error:function(xhr,textStatus,errorThrown){}
}
);
}
);
}
);
2,html代码
<!-- Ajax Asynchronous request test -->
<div id="container">
<table class="zebra">
<thead>
<tr>
<th>Ajax Asynchronous request test</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="button" name="determine_url" id="input_url" value="下面显示ajax<a href="http://www.cfei.net/archives/tag/%e5%bc%82%e6%ad%a5" title="浏览关于“异步”的文章" target="_blank" class="tag_link">异步</a>请求的数据,数据来自服务器端"/></td>
</tr>
</tbody>
</table>
</div>
<!-- Display the response body -->
<div id="response_div"></div>
3,服务器端代码 SpringMVC的Controller
<span style="font-size:14px;">/**
*
* @author ycq
*
* Ajax Asynchronous request test
*
*/
@Controller
public class AjaxAsynchronousRequestTestController {
@RequestMapping("AjaxAsynchronousRequestTest.action")
@ResponseBody
public Map<String,String> getBeanBySpringMethod(){
//创建一个Map,用来封装数据
Map<String,String> responseToAjax = new HashMap<String,String>();
responseToAjax.put("message", "ajax请求数据接收成功...");
responseToAjax.put("msg", "@ResponseBody");
//测试输出
System.out.println("测试...,打印这段文字,说明Ajax Asynchronous request 发送成功...");
return responseToAjax;
}
}</span>
jqueryajaxcdn异步springmvc
因为水平有限,难免有疏忽或者不准确的地方,希望大家能够直接指出来,我会及时改正。一切为了知识的分享。
后续会有更多的精彩的内容分享给大家。
支付宝扫一扫
微信扫一扫
