jQuery中Ajax-ajax方法

* jQuery中的Ajax
        * load()
        * $.get()
        * $.post()
        * $.ajax()
        * $.getScript():动态加载脚本

        * $.getJSON()


AJAX方法

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
    <head>
        <title>ajax()方法</title>
        <meta http-equiv="content-type" content="text/html; charset=UTF-8">
        <script type="text/javascript" src="../js/jquery-1.10.2.js">
        </script>
        <style type="text/css">
            div, span {
                width: 140px;
                height: 140px;
                margin: 20px;
                background: #9999CC;
                border: #000 1px solid;
                float: left;
                font-size: 17px;
                font-family: Roman;
            }
            
            div.mini {
                width: 30px;
                height: 30px;
                background: #CC66FF;
                border: #000 1px solid;
                font-size: 12px;
                font-family: Roman;
            }
            
            div.visible {
                display: none;
            }
        </style>
        <!--引入jquery的js库-->
    </head>
    <body>
        <form action="" name="form1" id="form1">
            <input type="text" name="username" id="username" value="zhang">
            <br>
            <input type="text" name="psw" id="psw" value="99999">
            <br>
            <input type="button" id="b1" value="登陆">
        </form>
        <div id="one">
        </div>
    </body>
    <script language="JavaScript">
        $().ready(function(){
            $("#b1").click(function(){
              $("#b1").click(function(){
						/*
						 * $.ajax(options);
						 * 	* options:{
						 * 					key : value
						 * 			   }
						 */
						var json = {
							username : $("#username").val(),
							psw : $("#psw").val()
						}
						
						$.ajax({
							url:"load.jsp",
							type:"get",
							async:true,
							data:json,
							dataType:"xml",
							success:function(data,textStatus){
								alert(data);
							},
							error:function(XMLHttpRequest,textStatus,errorThrown){
								alert("请求出错啦。。。");
							}
						});
					});
            });
            
            
        });
    </script>
</html>

<%@ page language="java" pageEncoding="UTF-8"%>
<% 
	System.out.println(request.getMethod());

	System.out.println("connection server success");

	System.out.println("username = "+request.getParameter("username"));
	System.out.println("password = "+request.getParameter("psw"));
	
	//响应HTML格式
	//out.println("helloworld");
	
	//响应XML格式
	response.setContentType("text/xml;charset=utf-8");
	out.println("<china><province name='吉林省'></province><province name='辽宁省'></province><province name='山东省'></province></china>");

%>

$.getScript()动态加载脚本

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>getScript()方法</title>
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="this is my page">
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
	<script type="text/javascript" src="../js/jquery-1.4.2.js"></script>
	<style>
		* { margin:0; padding:0;}
		body { font-size:12px;}
		.comment { margin-top:10px; padding:10px; border:1px solid #ccc;background:#DDD;}
		.comment h6 { font-weight:700; font-size:14px;}
		.para { margin-top:5px; text-indent:2em;background:#DDD;}
		.block{width:80px;height:80px;background:#DDD;}
	</style>
  </head>
  <body>
	 <br/>
	 <p>
		 <input type="button" id="send" value="加载"/>
	 </p>
	
	<div  class="comment">已有评论:</div>
	 <div id="resText" >
		
	 </div>
  </body>
  <script type="text/javascript">
   $(function(){
        $('#send').click(function() {
			 $.getScript('test.js');
        });
   })
   
   //$(function(){})  ==  $().ready(function(){})
  </script>
</html>

var comments = [
  {
    "username": "张三",
    "content": "沙发."
  },
  {
    "username": "李四",
    "content": "板凳."
  },
  {
    "username": "王五",
    "content": "地板."
  }
];

  var html = '';
  $.each( comments , function(commentIndex, comment) {
      html += '<div class="comment"><h6>' + comment['username'] + ':</h6><p class="para">' + comment['content'] + '</p></div>';
  })

  $('#resText').html(html);

$.getJSON()

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>getJSON()方法</title>
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="this is my page">
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
	<script type="text/javascript" src="../js/jquery-1.4.2.js"></script>
	<style>
		* { margin:0; padding:0;}
		body { font-size:12px;}
		.comment { margin-top:10px; padding:10px; border:1px solid #ccc;background:#DDD;}
		.comment h6 { font-weight:700; font-size:14px;}
		.para { margin-top:5px; text-indent:2em;background:#DDD;}
		.block{width:80px;height:80px;background:#DDD;}
	</style>
  </head>
  <body>
	 <br/>
	 <p>
		 <input type="button" id="send" value="加载"/>
	 </p>
	
	<div  class="comment">已有评论:</div>
	 <div id="resText" >
		
	 </div>
  </body>
  <script type="text/javascript">
   $(function(){
        $('#send').click(function() {
			 $.getJSON("test.json",function(data){
			 	$('#resText').empty();
				  var html = '';
				  $.each( data  , function(commentIndex, comment) {
					  html += '<div class="comment"><h6>' + comment['username'] + ':</h6><p class="para">' + comment['content'] + '</p></div>';
				  })
				 $('#resText').html(html);
			 });
       })
   })
  </script>
</html>

test.json

[
  {
    "username": "张三",
    "content": "沙发."
  },
  {
    "username": "李四",
    "content": "板凳."
  },
  {
    "username": "王五",
    "content": "地板."
  }
]

实现跨域请求


 <script type="text/javascript">
  		$().ready(function(){
  			$("#send").click(function(){
  				$.getJSON("http://www.sina.com.cn",function(){
  					alert("请求成功了");
  				});
  			});
  		});
  		
  </script>

public class TestServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		
		System.out.println("connection sina success!");
		
		String callback = request.getParameter("callback");
		
		//jQuery110207728844861803689_1376708238782
		System.out.println("callback = "+callback);
		
		String json = "{msg:'sina news'}";
		
		//函数名(响应数据)
		out.println(callback+"("+json+")");
		
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doGet(request, response);
	}

}

把服务器的serverlet和index.jsp 用tomcat放在不同的主机名下


跨域请求 能请求成功 但是不能响应成功

l 什么是 JSONP

JSONPJSONwith Padding)是数据交换格式 JSON 的一种使用模式,可以让网页从别的网域要资料。

由于同源策略,一般来说位于 server.example.com 的网页无法与不是 server.example.com 的服务器沟通,而HTML <script> 元素是一个例外。利用<script> 元素的这个开放策略,网页可以得到从其他来源动态产生的 JSON 资料,而这种使用模式就是所谓的 JSONP


<script type="text/javascript">
  		$().ready(function(){
  			$("#send").click(function(){
  				$.getJSON("http://www.sina.com.cn/testServlet?callback?",function(data){
  					alert("请求成功了");
  					alert(data);
  				});
  			});
  		});
  		
  </script>
?代表回掉函数  因为这个函数是匿名的 所以用?代表


这个解决办法不好 这里就不再介绍

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值