• 【jQuery】jQuery与Ajax的应用


    1.demo1

    <script language="javascript" type="text/javascript">
    //通过这个函数来异步获取信息
    function Ajax(){ 
        var xmlHttpReq = null;    //声明一个空对象用来装入XMLHttpRequest
        if (window.ActiveXObject){//IE5 IE6是以ActiveXObject的方式引入XMLHttpRequest的
            xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
        } 
        else if (window.XMLHttpRequest){//除IE5 IE6 以外的浏览器XMLHttpRequest是window的子对象
            xmlHttpReq = new XMLHttpRequest();//实例化一个XMLHttpRequest
        }
        if(xmlHttpReq != null){    //如果对象实例化成功 
            xmlHttpReq.open("GET","test.php",true);    //调用open()方法并采用异步方式
            xmlHttpReq.onreadystatechange=RequestCallBack; //设置回调函数
            xmlHttpReq.send(null);    //因为使用get方式提交,所以可以使用null参调用
        }
        function RequestCallBack(){//一旦readyState值改变,将会调用这个函数
            if(xmlHttpReq.readyState == 4){
                    if(xmlHttpReq.status == 200){
                        //将xmlHttpReq.responseText的值赋给ID为 resText 的元素
                        document.getElementById("resText").innerHTML = xmlHttpReq.responseText;
                    }
            }
        }
    }
    </script>
    </head>
    <body>
    <input type="button" value="Ajax提交" onclick="Ajax();" />
    <div id="resText" ></div>
    </body>

    2.load()方法:能载入远程HTML代码并插入DOM中

    <script language="javascript" type="text/javascript">
      $(function(){
          $("#send").click(function(){
                  $("#resText").load("test.html");
          })
      })
    </script>
    </head>
    <body>
    <input type="button" id="send" value="Ajax获取" />
    
    <div  class="comment">
        已有评论:
    </div>
    <div id="resText" ></div>
    </body>

    点击前后结果如下

                      

    3.如果需要传递一些参数给服务器的页面,可以使用$get()或$post()

    3.1 $get()

     <!--   引入jQuery -->
    <script src="../scripts/jquery.js" type="text/javascript"></script>
    <script type="text/javascript">
    //<![CDATA[
        $(function(){
           $("#send").click(function(){
                $.get("get1.php", { //发送给get1.php的数据
                            username :  $("#username").val() , 
                            content :  $("#content").val()  
                        }, function (data, textStatus){
                            $("#resText").html(data); // 回调,把返回的数据添加到页面上,还可以采用XML、json格式
                        }
                );
           })
        })
    //]]>
    </script>
    </head>
    <body>
    <form id="form1" action="#">
    <p>评论:</p>
     <p>姓名: <input type="text" name="username" id="username" /></p>
     <p>内容: <textarea name="content" id="content"  rows="2" cols="20"></textarea></p>
     <p><input type="button" id="send" value="提交"/></p>
    </form>
    
    
    <div  class='comment'>已有评论:</div>
    <div id="resText" >
    </div>
    
    </body>

    get1.php

    <?php 
        header("Content-Type:text/html; charset=utf-8");
        echo "<div class='comment'><h6>{$_REQUEST['username']}:</h6><p class='para'>{$_REQUEST['content']}</p></div>";
    ?>

    3.2 $post()

    与$get()方法的结构和使用方式都相同,但也存在以下区别

    a.参数跟的位置不同

    b.GET对传输数据有限制,请求的数据会被缓存,存在安全隐患

    c.传递的数据在服务端获取的方式不同,PHP中数据通过$_GET[],$_POST[]获取,两种方式都可通过$_REQUEST[]获取

    4  $.getScript()和$.getJson()--第三层

    4.1 jQuery提供了$.getScript()方法直接加载js文件,也可以添加回掉函数

    4.2 $.getJson()加载json文件

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

     
    1、选择器+遍历
    $('div').each(function (i){
       i就是索引值
       this 表示获取遍历每一个dom对象
    });
    2、选择器+遍历
    $('div').each(function (index,domEle){
       index就是索引值
      domEle 表示获取遍历每一个dom对象
    });
    3、更适用的遍历方法
    1)先获取某个集合对象
    2)遍历集合对象的每一个元素
    var d=$("div");
    $.each(d,function (index,domEle){
      d是要遍历的集合
      index就是索引值
      domEle 表示获取遍历每一个dom对
    });

    这里属于第三类:

     <!--   引入jQuery -->
    <script src="../scripts/jquery.js" type="text/javascript"></script>
    <script type="text/javascript">
    //<![CDATA[
       $(function(){
            $('#send').click(function() {
                 $.getJSON('test.json', function(data) {
                     $('#resText').empty();
                      var html = '';
                      $.each( data  , function(commentIndex, comment) {//jQuery通用的遍历方法$.each()
                          html += '<div class="comment"><h6>' + comment['username'] + ':</h6><p class="para">' + comment['content'] + '</p></div>';
                      })
                     $('#resText').html(html);
                })
           })
       })
    //]]>
    </script>
    </head>
    <body>
     <br/>
     <p>
         <input type="button" id="send" value="加载"/>
     </p>
    
    <div  class="comment">已有评论:</div>
     <div id="resText" >
        
     </div>
    
    </body>

    test.json

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

    5 $.ajax()方法

    它是jQuery最底层的Ajax实现

    6 serialize()

    jQuery提供一种简化的方法来提交表单,不用一一列举表单元素,而是直接使用serialize(),它能将DOM元素内容序列化为字符串。

    即使在表单中在增加字段,脚本仍能使用

    </style>
     <!--   引入jQuery -->
    <script src="../scripts/jquery.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(function(){
           $("#send").click(function(){
                $.get("get1.php", $("#form1").serialize() , function (data, textStatus){
                            $("#resText").html(data); // 把返回的数据添加到页面上
                        }
                );
           })
        })
    </script>
    </head>
    <body>
    <form id="form1" action="#">
    <p>评论:</p>
     <p>姓名: <input type="text" name="username" id="username" /></p>
     <p>内容: <textarea name="content" id="content"  rows="2" cols="20"></textarea></p>
     <p><input type="button" id="send" value="提交"/></p>
    </form>
    
    <div  class='comment'>已有评论:</div>
    <div id="resText" >
    </div>
    
    </body>

     7 $.param()

    <script type="text/javascript">
    //<![CDATA[
        $(function(){
              var obj={a:1,b:2,c:3};
            var  k  = $.param(obj);
            alert(k)        // 输出  a=1&b=2&c=3
        })
    //]]>
    </script>

    8 Ajax全局事件

    Ajax请求开始时,会触发ajaxStart()方法的回调函数;

    Ajax请求结束时,会触发ajaxStop()方法的回调函数;

     

    <script src="../scripts/jquery.js" type="text/javascript"></script>
    <script type="text/javascript">
    //<![CDATA[
       $(function(){
        //demo1:
            $('#send1').click(function() {
                $.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?tags=car&tagmode=any&format=json&jsoncallback=?",
                          function(data){
                              $("#resText1").empty();
                              $.each(data.items, function( i,item ){
                                    $("<img/> ").attr("src", item.media.m ).appendTo("#resText1");
                                    if ( i == 3 ) { 
                                        return false;
                                    }
                              });
                         }
                ); 
           });
    
       //demo2:
           $("#send2").click(function(){
                $.get("get1.php", { 
                            username :  $("#username").val() , 
                            content :  $("#content").val()  
                        }, function (data, textStatus){
                            $("#resText2").html(data); // 把返回的数据添加到页面上
                        }
                );
           })
    
            $.ajaxPrefilter(function( options ) {
                options.global = true;
            });
            //共用这2个全局的ajax事件
           $("#loading").ajaxStart(function(){
              $(this).show();
           });
           $("#loading").ajaxStop(function(){
              $(this).hide();
           });
    
    
       })
    //]]>
    </script>
    </head>
    <body>
    <br/>
    <div id="loading">加载中...</div>
    
    <br/>
    Demo1:
    <br/>
    <input type="button" id="send1" value="加载"/>
    <div id="resText1" ></div>
    
    
    <br/>
    Demo2:
    <br/>
    <form id="form1" action="#">
    <p>评论:</p>
     <p>姓名: <input type="text" name="username" id="username" /></p>
     <p>内容: <textarea name="content" id="content"  rows="2" cols="20"></textarea></p>
     <p><input type="button" id="send2" value="提交"/></p>
    </form>
    <div  class='comment'>已有评论:</div>
    <div id="resText2" >
    </div>
    
    
    </body>

     

  • 相关阅读:
    电机驱动MCU通用功能和技术点解析
    串行SPI NOR闪存VS并行NOR闪存
    非易失性存储器Flash和EEPROM之间的差异与优缺点
    为何要使用MCU
    MRAM实现对车载MCU中嵌入式存储器的取代
    ​弥补现有MRAM的不足
    将赛普拉斯nvSRAM替换为MRAM
    PSRAM在数据缓冲应用中可以取代SRAM或SDRAM
    数据库建表语句备份(二)
    数据库建表语句备份(一)
  • 原文地址:https://www.cnblogs.com/yujihang/p/6876025.html
Copyright © 2020-2023  润新知