Ajax请求小结
本人对Ajax的几种请求做了整理,提供给大家学习
一、简单的Ajax请求
<script> $(function() { $("input[type='button']").bind("click", function() { /**Ajax的请求*/ $.ajax( { //请求的路径 url : "json.html", //是否异步 async : true, //请求的方法 type : "get", //请求成功时调用 success : function(msg) { alert(msg); }, //请求失败时调用 error : function(msg) { alert(msg); } }); }); }); </script>
<!—body部分-->
<body>
<input type="button" value="Ajax请求" />
</body>
二、Ajax请求jsp(传参数)
1、get请求
<script type="text/javascript"> $(function(){ $("input[type='button']").bind("click",function(){ /**Ajax的请求*/ $.ajax({ //请求的路径及所传的参数 url:"user.jsp?name=kouxiaolin", //是否异步 async:true, //请求的方法 type:"get", //请求成功时调用 success:function(msg){ alert(msg); }, //请求失败时调用 error:function(msg){ alert(msg); } }); }); }); </script>
<!—user.jsp-->
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String name = request.getParameter("name");
if("kouxiaolin".equals(name)){
out.print("用户名正确");
}else{
out.println("用户名错误");
}
%>
2、post请求
<script> $(function() { //参数也可以在前面定义好,然后再后面调用 // var obj={name:"kouxiaolin",pass:"123"}; $("input[type='button']").bind("click", function() { /**Ajax的请求*/ $.ajax( { //请求的路径 url : "user.jsp", //是否异步 async : true, //请求方式 type : "post", //所传参数多个参数用&连接:data:"name=kouxiaolin&pass=123" data:"name=kouxiaolin", //data:obj, //请求成功时调用 success : function(msg) { alert(msg); }, //请求失败时调用 error : function(msg) { alert(msg); } }); }); }); </script>
三、Ajax请求解析json
<script> $(function() { $("input[type='button']").bind("click", function() { /**Ajax的请求*/ $.ajax( { //请求路径 url : "user.html", //是否异步 async : true, //请求的方法 type : "get", //请求成功是调用 success : function(msg) { alert(msg.name);//返回kouxiaolin }, //请求失败时调用 error : function(msg) { alert(msg); }, //请求解析返回的类型是json类型 dataType:"json" }); }); }); </script>
<!—user.html-->