您的位置:首页 > Web前端 > JQuery

SpringMVC框架下,通过jQuery发送ajax异步(asynchronous)请求

2016-01-14 18:30 756 查看
一,如何在项目中引用jQuery

jQuery官方CDN

<span style="font-size:14px;"><script type="text/javascript" src="http://code.jquery.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 + SpringMVC 
$(function(){
    //文本框点击事件
    $("#input_url").click(
        function(){
            //
            var $a = $(this);
            //发送ajax请求
            $.ajax({
                //
                url:"AjaxAsynchronousRequestTest.action",
                type:'post',
                data:'name=admin',
                dataType:'json',
                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异步请求的数据,数据来自服务器端"/></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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: