index.htmlphp
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="jquery-3.3.1.min.js"></script> <!--<script src="http://libs.baidu.com/jquery/2.1.1/jquery.min.js"></script>--> <script> /*AJAX請求很是方便,底層已經封裝好了*/ /*實現只修改頁面一部份內容而不使頁面刷新*/ $(document).ready(function(){ $("#btn").click(function(){ $("#result").text("請求數據中,請稍後");/*提高用戶體驗*/ $.get("Server2.php",{name:$("#namevalue").val()},function(data){ alert("hello"); $("#result").text(data); /*這裏是get方式,若是想改爲post方式直接把js文件中的get和php文件中的get改爲post就好了*/ }).fail(function(){ $("#result").text("通信有問題"); /*視頻教程裏面用的是.error函數,可是視頻是12年的太老了,因此可能會有錯誤,這裏要用fail函數, * 看來視頻也仍是要跟着時代走的啊!!!*/ }); }); }).ajaxError(function(event, jqxhr, settings, exception) { console.log(event); console.log(jqxhr); alert(settings.url);/*setting能夠得到究竟是哪個請求出錯了。*/ // if ( settings.url == "http://localhost:9090/Server1.php" ) { // $( "#result" ).text( "Triggered ajaxError handler." ); // } }); </script> </head> <body> <input type="text" id="namevalue"> <br/> <button id="btn">send</button> 結果:<span id="result"></span> </body> </html>
Server.phphtml
<?php /** * Created by PhpStorm. * User: lin * Date: 2018/12/14 * Time: 14:39 */ if(isset($_GET['name'])){ echo "hello:".$_GET['name']; }else{ echo "Args Error(參數錯誤)"; }
加載片斷:jquery
加載片斷.htmlajax
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="jquery-3.3.1.min.js"></script> <script> $(document).ready(function(){ $("body").text("wait...."); // alert("hello"); $("body").load("box.htm",function(a,status,c){/*加載一個盒子*/ console.log(status); if(status == "error"){ $("body").text("片斷加載失敗!"); } }) $.getScript("helloJS.js",function(){ sayHello();/*這樣是能夠的,多是教學視頻有點老了,有不少不對應的地方,他竟然用了complete方法, 我在官方文檔中就沒有查到這個方法。*/ /*getScript方法使用.fail()方法處理錯誤。並非error方法*/ }); }); /*.ajaxComplete(function( event, xhr, settings ) { alert(settings.url); if ( settings.url === "helloJS.js" ) { /!*這裏的setting沒法得到helloJS.js的信息,可是能得到box.htm的信息*!/ sayHello(); /!*異步加載的方式就是爲了更好的用戶體驗。 這裏能夠實現當加載完js文件的時候彈出一個對話框*!/ } });*/ </script> </head> <body> </body> </html>
box.htm異步
<div style="width:100px; height:100px; background-color: #ff0000"></div>
helloJS.js函數
function sayHello(){ alert("hello ajax"); }