執行個體
通過 AJAX 載入一段文本:
jQuery 代碼:
| 代碼如下 |
複製代碼 |
$(document).ready(function(){ $("#b01").click(function(){ htmlobj=$.ajax({url:"/jquery/test1.txt",async:false}); $("#myDiv").html(htmlobj.responseText); }); }); |
HTML 程式碼:
| 代碼如下 |
複製代碼 |
<div id="myDiv"><h2>Let AJAX change this text</h2></div> <button id="b01" type="button">Change Content</button> |
簡單ajax使用者註冊
前台檔案:
| 代碼如下 |
複製代碼 |
<script type="text/javascript" src="js/jque第二世界整理髮布ry.js" mce_src="js/jquery.js"></script> <input name="writer" id="writer" type="text" value="" /> <input name="pass" id="pass" type="password" value="" /> <input type="submit" name="button" id="button" value="提交" /> <!--這裡不需要form,因為提交時call一個函數 <script type="text/javascript"> $(document).ready(function(){ //DOM的onload事件處理函數 $("#button").click(function(){ //當按鈕button被點擊時的處理函數 postdata(); //button被點擊時執行postdata函數 }); }); function postdata(){ //提交資料函數 $.ajax({ //調用jquery的ajax方法 type: "POST", //設定ajax方法提交資料的形式 url: "ok.php", //把資料提交到ok.php data: "writer="+$("#writer").val()+"&pass="+$("#pass").val(), //輸入框writer中的值作為提交的資料 success: function(msg){ //提交成功後的回調,msg變數是ok.php輸出的內容。 alert("資料提交成功"); //如果有必要,可以把msg變數的值顯示到某個DIV元素中 } }); } </script> |
後台檔案:
| 代碼如下 |
複製代碼 |
<?php require "config.php"; require "conn.php"; $writer=$_POST['writer']; $pass=$_POST['pass']; mysql_query("insert into user values(0,'$writer','$pass')",$db); //echo $_POST['writer']; ?> |
利用iframe方法實現無重新整理提交
利用iframe來做無重新整理上傳
要實現檔案上傳,form必須設定幾個屬性:
1.action:設為要處理資料的頁面地址;
2.method:設為"post";
3.enctype/encoding:必須設為"multipart/form-data",這裡要注意的是在ie中用js修改form的enctype屬性是沒有效果的,只能修改encoding;
iframe實現無重新整理上傳的原理:利用form的target屬性,把資料提交到頁面中一個(通常為隱藏的)iframe上。直觀點說就是把“重新整理”留給iframe。
其實原理跟一般用iframe實現無重新整理提交表單是一樣的,只是這裡換成是檔案。
這裡關鍵就是把form的target設為iframe的name
iframe的具體樣本:
| 代碼如下 |
複製代碼 |
<html> <body> <iframe src="a.htm" frameborder=“0” scrolling="yes" height="100px" width="100px"></iframe> </body> </html>
|
這個在頁面上顯示為一個嵌在頁面的架構,該架構的大小為長100像素,寬100像素,有捲軸沒有邊框。
| 代碼如下 |
複製代碼 |
<html> <body> <iframe name="res" style="display:none;" src="a.htm" frameborder=“0” scrolling="yes" height="100px" width="100px"></iframe> <form target="res"> </form>
|
用隱含的iframe提交資料,可以避免頁面重新整理。
</body>
</html>