jQuery簡單的Ajax調用示例

jQuery確實方便,下面作個簡單的Ajax調用:javascript

創建一個簡單的html文件:php

<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript" src="Public/js/jquery-easyui-1.3.1/jquery-1.8.2.min.js"></script>
<script type="text/javascript"> $(function(){ //按鈕單擊時執行
 $("#testAjax").click(function(){ //取Ajax返回結果
              //爲了簡單,這裏簡單地從文件中讀取內容做爲返回數據
 htmlobj=$.ajax({url:"/Readme.txt",async:false}); //顯示Ajax返回結果
 $("#myDiv").html(htmlobj.responseText); }); }); </script>    
</head>
    <body>
        <div id="myDiv"><h2>經過 AJAX 改變文本</h2></div>
        <button id="testAjax" type="button">Ajax改變內容</button>
    </body>
</html>

好了,點擊按鈕就能夠看到效果了。html

固然,jQuery的Ajax調用能夠控制項不少,這裏演示了簡單的調用。java

注意你本身的jquery引用路徑。jquery

 

好吧,作一個調用後臺的例子:ajax

<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript" src="Public/js/jquery-easyui-1.3.1/jquery-1.8.2.min.js"></script>
<script type="text/javascript"> $(function(){ //按鈕單擊時執行
 $("#testAjax").click(function(){ //Ajax調用處理
            var html = $.ajax({ type: "POST", url: "test.php", data: "name=garfield&age=18", async: false }).responseText; $("#myDiv").html('<h2>'+html+'</h2>'); }); }); </script>    
</head>
    <body>
        <div id="myDiv"><h2>經過 AJAX 改變文本</h2></div>
        <button id="testAjax" type="button">Ajax改變內容</button>
    </body>
</html>

後臺代碼:async

<?php $msg='Hello,'.$_POST['name'].',your age is '.$_POST['age'].'!'; echo $msg;

如今已經能夠從後臺來獲取數據了!函數

 

固然,咱們還能夠這樣來調用Ajax:post

<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript" src="Public/js/jquery-easyui-1.3.1/jquery-1.8.2.min.js"></script>
<script type="text/javascript"> $(function(){ //按鈕單擊時執行
 $("#testAjax").click(function(){ //Ajax調用處理
 $.ajax({ type: "POST", url: "test.php", data: "name=garfield&age=18", success: function(data){ $("#myDiv").html('<h2>'+data+'</h2>'); } }); }); }); </script>    
</head>
    <body>
        <div id="myDiv"><h2>經過 AJAX 改變文本</h2></div>
        <button id="testAjax" type="button">Ajax改變內容</button>
    </body>
</html>

 

注意,ui

success: function(data)

中的data參數能夠改成別的名稱,好比success: function(msg),msg(data)爲返回的數據。 此處爲回調函數的參數,而非

data: "name=garfield&age=18"

中的Ajax調用中的data參數。

相關文章
相關標籤/搜索