本文實(shí)例講述了jQuery實(shí)現(xiàn)簡(jiǎn)單的Ajax調(diào)用功能。分享給大家供大家參考,具體如下:
這里的jQuery調(diào)用為CDN地址://cdn.bootcss.com/jquery/3.3.1/jquery.min.js
jQuery確實(shí)方便,下面做個(gè)簡(jiǎn)單的Ajax調(diào)用:
建立一個(gè)簡(jiǎn)單的html文件:
<!DOCTYPE HTML><html><head><script type="text/javascript" src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script><script type="text/javascript"> $(function(){ //按鈕單擊時(shí)執(zhí)行 $("#testAjax").click(function(){ //取Ajax返回結(jié)果 //為了簡(jiǎn)單,這里簡(jiǎn)單地從文件中讀取內(nèi)容作為返回?cái)?shù)據(jù) htmlobj=$.ajax({url:"/Readme.txt",async:false}); //顯示Ajax返回結(jié)果 $("#myDiv").html(htmlobj.responseText); }); });</script></head> <body> <div id="myDiv"><h2>通過(guò) AJAX 改變文本</h2></div> <button id="testAjax" type="button">Ajax改變內(nèi)容</button> </body></html>好了,點(diǎn)擊按鈕就可以看到效果了。
當(dāng)然,jQuery的Ajax調(diào)用可以控制項(xiàng)很多,這里演示了簡(jiǎn)單的調(diào)用。
注意你自己的jquery引用路徑。
好吧,做一個(gè)調(diào)用后臺(tái)的例子:
<!DOCTYPE HTML><html><head><script type="text/javascript" src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script><script type="text/javascript"> $(function(){ //按鈕單擊時(shí)執(zhí)行 $("#testAjax").click(function(){ //Ajax調(diào)用處理 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>通過(guò) AJAX 改變文本</h2></div> <button id="testAjax" type="button">Ajax改變內(nèi)容</button> </body></html>后臺(tái)test.php文件代碼:
<?php $msg='Hello,'.$_POST['name'].',your age is '.$_POST['age'].'!'; echo $msg;
當(dāng)然,我們還可以這樣來(lái)調(diào)用Ajax:
<!DOCTYPE HTML><html><head><script type="text/javascript" src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script><script type="text/javascript"> $(function(){ //按鈕單擊時(shí)執(zhí)行 $("#testAjax").click(function(){ //Ajax調(diào)用處理 $.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>通過(guò) AJAX 改變文本</h2></div> <button id="testAjax" type="button">Ajax改變內(nèi)容</button> </body></html>
新聞熱點(diǎn)
疑難解答
圖片精選