jQuery 中 ajax 請求資料應用的一個小demo

來源:互聯網
上載者:User

標籤:style   http   color   使用   strong   io   檔案   資料   

舉一個jquery中ajax的應用小 demo 便於以後的更多項目拓展 ,這裡要注意的是儲存的檔案名稱和檔案圖片路徑問題 ...

 

ajax01.html

 

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title> ajax小例子 </title>

</head>

 

<body>

 

 <!-- 擷取ajax資料的觸發按鈕 -->

 <input type="button" value="擷取資料" class="btn">

 

 

<!-- 讓 ajax 內容載入到 news 這個 div 中 -->

<div class="news">

 

 <img src="img/loading.gif" class="load" style="display:none;">

 

</div><!--news-->

 

 

</body>

 

</html>

 

<script src="jquery-1.8.2.min.js"></script>

<script>

 

 $(function(){

 

  //在整個文檔中指定ajax開始與結束載入圖片的顯示與隱藏

  $(document).ajaxStart(function(){

 

  //資料還未載入完成的時候 load 圖片展示

  $(‘.load‘).show();

  }).ajaxStop(function(){

 

  //資料載入完成的時候 load 圖片消失

  $(‘.load‘).hide();

  })

   

    //按鈕點擊的時候那麼觸發ajax

  $(‘.btn‘).click(function(){

 

         $.ajax({

            

            //要擷取到的ajax的php檔案,記得要在後面加上隨機數清除緩衝

          url:‘ajax01.php?t=‘+ Math.random(),

 

            //類型使用get方式,這個要與程式員約定

          type:‘GET‘, 

 

          //設定一個網路逾時時間,如果一旦過了這個時間還未請求成功的話,那麼就在 error 這個屬性上設定錯誤報表

           timeout:5000,

 

            //成功的話執行一段函數來進行功能實現

          success:function(data){

 

               //data是返回來的資料,資料類型為字串型,那麼要經過eval方法來進行轉換成對象

          var result = eval(data);  

 

             //使用 for in 語句來進行遍曆

             for(var i in result){

 

                    //得到資料插入到要輸出的元素中

                var child = $(‘<div class="child"><h3>‘+result[i].title+‘</h3><p>‘+result[i].content+‘</p></div>‘);

 

                 //再把元素插入到new這個盒子裡面

                    $(‘.news‘).append(child);

                }

           }   

        

          //如果發生錯誤的錯誤報表

          error:function( XMLHttpRequest, textStatus, errorThrown ){

 

                  //如果網路逾時了那麼執行提示

                   if (textStatus == ‘timeout‘) {

                               alert(‘網路逾時,請重新整理!‘);

                             }

                      }

 

       });

    });

 });

</script>

 

 

ajax01.php

 

<?php 

 

 //睡眠1秒是為了測試是否會執行load圖片的顯示

 sleep(1);

 

 //輸出json格式的資料

 echo ‘[{"title":"第一現場","content":"我是內容一"},

        {"title":"第二現場","content":"我是內容二"},

        {"title":"第三現場","content":"我是內容三"}]‘;

 

 ?>

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.