javascript之jQuery ajax 操作

来源:互联网 发布:王克勤记者知乎 编辑:程序博客网 时间:2024/05/20 23:38

ajax不足

1.浏览器的支持度不够,IE 5以后才支持

2.破坏浏览器的前进,后退功能

3.搜索引擎的支持度不同

4.开发调试工具缺乏

三层方法

1.$.ajax()最底层方法

2.$.load(),$.get(),$.post()最常用

3.$.getScript(),$.getJSON()方法

load方法

[javascript] view plaincopy在CODE上查看代码片派生到我的代码片
  1.   $(function(){  
  2.       $("#send").click(function(){  
  3.               $("#resText").load("test.html");  
  4.       })  
  5.   })  
  6.   $(function(){  
  7.       $("#send").click(function(){  
  8.               $("#resText").load("test.html .para");  
  9.       })  
  10.   })  
  11.   $(function(){  
  12.       $("#send").click(function(){  
  13.               $("#resText").load("test.html .para",function (responseText, textStatus, XMLHttpRequest){  
  14.                          alert( $(this).html() );    //在这里this指向的是当前的DOM对象,即 $("#iptText")[0]  
  15.                          alert(responseText);       //请求返回的内容  
  16.                          alert(textStatus);            //请求状态:success,error,notmodified,timeout  
  17.                          alert(XMLHttpRequest);     //XMLHttpRequest对象  
  18.             });  
  19.       })  
  20.   })  
  21. //无论ajax是否请求成功,只要当请求完成后,回调函数就被触发.   

get方法

[javascript] view plaincopy在CODE上查看代码片派生到我的代码片
  1. //<![CDATA[  
  2.     $(function(){  
  3.        $("#send").click(function(){  
  4.             $.get("get1.php", {   
  5.                         username :  $("#username").val() ,   
  6.                         content :  $("#content").val()    
  7.                     }, function (data, textStatus){  
  8.                         $("#resText").html(data); // 把返回的数据添加到页面上  
  9.                     }  
  10.             );  
  11.        })  
  12.     })  
  13. //]]>  
  14. //返回HTML格式,在不需要与其他应用程序共享数据的时候,使用HTML最为简单  
  15.  <?php   
  16.     header("Content-Type:text/html; charset=utf-8");  
  17.     echo "<div class='comment'><h6>{$_REQUEST['username']}:</h6><p class='para'>{$_REQUEST['content']}</p></div>";  
  18. ?>  
[javascript] view plaincopy在CODE上查看代码片派生到我的代码片
  1. //<![CDATA[  
  2.     $(function(){  
  3.        $("#send").click(function(){  
  4.             $.get("get2.php", {   
  5.                         username :  $("#username").val() ,   
  6.                         content :  $("#content").val()    
  7.                     }, function (data, textStatus){  
  8.                         var username = $(data).find("comment").attr("username");  
  9.                         var content = $(data).find("comment content").text();  
  10.                         var txtHtml = "<div class='comment'><h6>"+username+":</h6><p class='para'>"+content+"</p></div>";  
  11.                         $("#resText").html(txtHtml); // 把返回的数据添加到页面上  
  12.                     });  
  13.        })  
  14.     })  
  15. //]]>  
  16. //返回XML格式,体积相对较大,解析和操作的速度都会慢一点  
  17. <?php   
  18.     header("Content-Type:text/xml; charset=utf-8");  
  19.     echo "<?xml version='1.0' encoding='utf-8'?>".  
  20.          "<comments>".  
  21.          "<comment username='{$_REQUEST['username'] }' >".  
  22.          "<content>{$_REQUEST['content']}</content>".  
  23.          "</comment>".  
  24.          "</comments>";  
  25. ?>  
[javascript] view plaincopy在CODE上查看代码片派生到我的代码片
  1. //<![CDATA[  
  2.     $(function(){  
  3.        $("#send").click(function(){  
  4.             $.get("get3.php", {   
  5.                         username :  $("#username").val() ,   
  6.                         content :  $("#content").val()    
  7.                     }, function (data, textStatus){  
  8.                         var username = data.username;  
  9.                         var content = data.content;  
  10.                         var txtHtml = "<div class='comment'><h6>"+username+":</h6><p class='para'>"+content+"</p></div>";  
  11.                         $("#resText").html(txtHtml); // 把返回的数据添加到页面上  
  12.                     },"json");  
  13.        })  
  14.     })  
  15. //]]>  
  16. //返回JSON文件  
  17. <?php   
  18.     header("Content-Type:text/html; charset=utf-8");  
  19.     echo "{ \"username\" : \"{$_REQUEST['username']}\" , \"content\" : \"{$_REQUEST['content']}\"}"   
  20. ?>   
[javascript] view plaincopy在CODE上查看代码片派生到我的代码片
  1. //<![CDATA[  
  2.     $(function(){  
  3.        $("#send").click(function(){  
  4.               $("#resText").load("get1.php?username="+$('#username').val()+"&content="+$('#content').val());  
  5.               //如果是中文需要编码  
  6.        })  
  7.     })  
  8. //]]>  

POST方法

1.GET请求会在URL进行传递,POST是作为消息实体发送给Web服务器

2.GET对传输的数据大小有限制,不大于2KB,POST方法理论上不受限制

3.GET方法请求的数据会被浏览器缓存起来,别人可以从历史记录中查看,存在安全问题

只需要修改$.get()为$.post()就可以,其它不变

[javascript] view plaincopy在CODE上查看代码片派生到我的代码片
  1. $(function(){  
  2.    $("#send").click(function(){  
  3.         $.post("post1.php", {   
  4.                     username :  $("#username").val() ,   
  5.                     content :  $("#content").val()    
  6.                 }, function (data, textStatus){  
  7.                        $("#resText").html(data); // 把返回的数据添加到页面上  
  8.                 }  
  9.         );  
  10.    })  
  11. })  
还可以使用load实现相同功能

[javascript] view plaincopy在CODE上查看代码片派生到我的代码片
  1. $(function(){  
  2.    $("#send").click(function(){  
  3.           $("#resText").load("post1.php",{   
  4.                     username :  $("#username").val() ,   
  5.                     content :  $("#content").val()    
  6.           })  
  7.    })  
  8. })  

$.getScript()

动态加载js文件

[javascript] view plaincopy在CODE上查看代码片派生到我的代码片
  1. $(function(){  
  2.      $('#send').click(function() {  
  3.           $.getScript('test.js');  
  4.      });  
  5. })  

设置回调函数

[javascript] view plaincopy在CODE上查看代码片派生到我的代码片
  1. //<![CDATA[  
  2.    $(function(){  
  3.              $.getScript('jquery.color.js',function(){  
  4.                   $("<p>加载JavaScript完毕</p>").appendTo("body");  
  5.                   $("#go").click(function(){  
  6.                        $(".block").animate( { backgroundColor: 'pink' }, 1000)  
  7.                                   .animate( { backgroundColor: 'blue' }, 1000);  
  8.                   });  
  9.              });  
  10.    })  
  11. //]]>  

$.getJSON()

$.each()函数不同于jQuery对象的each()方法,它是一个全局函数,不操作jQuery对象,而是以一个数组或者对象作为第1个参数,以一个回调函数作为第2个参数,回调函数拥有两个参数,第1个为对象的成员函数或数组的索引,第2个为对应变量或内容.

[javascript] view plaincopy在CODE上查看代码片派生到我的代码片
  1. //<![CDATA[  
  2.    $(function(){  
  3.         $('#send').click(function() {  
  4.              $.getJSON('test.json'function(data) {  
  5.                  $('#resText').empty();  
  6.                   var html = '';  
  7.                   $.each( data  , function(commentIndex, comment) {  
  8.                       html += '<div class="comment"><h6>' + comment['username'] + ':</h6><p class="para">' + comment['content'] + '</p></div>';  
  9.                   })  
  10.                  $('#resText').html(html);  
  11.             })  
  12.        })  
  13.    })  
  14. //]]>  

JSONP形式

从图片网站搜索汽车类别的4张最新图片

[javascript] view plaincopy在CODE上查看代码片派生到我的代码片
  1. //<![CDATA[  
  2.    $(function(){  
  3.         $('#send').click(function() {  
  4.             $.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?tags=car&tagmode=any&format=json&jsoncallback=?",  
  5.                       function(data){  
  6.                           $.each(data.items, function( i,item ){  
  7.                                 $("<img class='para'/> ").attr("src", item.media.m ).appendTo("#resText");  
  8.                                 if ( i == 3 ) {   
  9.                                     return false;  
  10.                                 }  
  11.                           });  
  12.                      }  
  13.             );   
  14.        })  
  15.    })  
  16. //]]>  

ajax方法实现get

[javascript] view plaincopy在CODE上查看代码片派生到我的代码片
  1. //<![CDATA[  
  2.    $(function(){  
  3.         $('#send').click(function() {  
  4.             $.ajax({  
  5.               type: "GET",  
  6.               url: "test.js",  
  7.               dataType: "script"  
  8.             });   
  9.         });  
  10.    })  
  11. //]]>  

serialize()方法

能够将DOM元素内容序列化为字符串,会自动编码

[javascript] view plaincopy在CODE上查看代码片派生到我的代码片
  1. $(function(){  
  2.    $("#send").click(function(){  
  3.         $.post("get1.jsp", $("#form1").serialize() , function (data, textStatus){  
  4.                        $("#resText").html(data); // 把返回的数据添加到页面上  
  5.                 }  
  6.         );  
  7.    })  
  8. })  

serializeArray()方法

不是返回字符串,而是将DOM元素序列化后,返回JSON格式的数据.

[javascript] view plaincopy在CODE上查看代码片派生到我的代码片
  1. $(function(){  
  2. var fields = $(":checkbox,:radio").serializeArray();  
  3. console.log(fields);// Firebug输出  
  4. $.each( fields, function(i, field){  
  5.    $("#results").append(field.value + " , ");  
  6. );   
  7. })  

$.param方法

[javascript] view plaincopy在CODE上查看代码片派生到我的代码片
  1. //<![CDATA[  
  2.     $(function(){  
  3.         var obj={a:1,b:2,c:3};  
  4.         var  k  = $.param(obj);  
  5.         alert(k)        // 输出  a=1&b=2&c=3  
  6.     })  
  7. //]]>  
  8. //用来对一个数组或对象按照key/value进行序列化  

ajax全局事件

[javascript] view plaincopy在CODE上查看代码片派生到我的代码片
  1. //可以为网页提供一个提示信息,常用的提示信息是"加载中"   
  2.   $(function(){  
  3.     //demo1:  
  4.         $('#send1').click(function() {  
  5.             $.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?tags=car&tagmode=any&format=json&jsoncallback=?",  
  6.                       function(data){  
  7.                           $("#resText1").empty();  
  8.                           $.each(data.items, function( i,item ){  
  9.                                 $("<img/> ").attr("src", item.media.m ).appendTo("#resText1");  
  10.                                 if ( i == 3 ) {   
  11.                                     return false;  
  12.                                 }  
  13.                           });  
  14.                      }  
  15.             );   
  16.        });  
  17.   
  18.    //demo2:  
  19.        $("#send2").click(function(){  
  20.             $.post("get1.jsp", {   
  21.                         username :  $("#username").val() ,   
  22.                         content :  $("#content").val()    
  23.                     }, function (data, textStatus){  
  24.                         $("#resText2").html(data); // 把返回的数据添加到页面上  
  25.                     }  
  26.             );  
  27.        })  
  28.   
  29.         $.ajaxPrefilter(function( options ) {  
  30.             options.global = true;  
  31.         });  
  32.         //共用这2个全局的ajax事件  
  33.        $("#loading").ajaxStart(function(){  
  34.           $(this).show();  
  35.        });  
  36.        $("#loading").ajaxStop(function(){  
  37.           $(this).hide();  
  38.        });  
  39.   
  40.   
  41.    })  
0 0
原创粉丝点击