- 15天學會jQuery編程與實戰(視頻教學版) (Web前端技術叢書)
- 劉鑫
- 178字
- 2020-11-28 16:21:46
3.7 利用Ajax直接執行返回的JS代碼
Ajax返回的類型可以是JS代碼,而且是可以直接運行的JS代碼,這需要通過$.getScript()實現,語法如下:
$.getScript( url [, success ] )
這其實也是$.ajax()的一種簡寫形式,復雜寫法如下:
$.ajax({ url: url, dataType: "script", success: success });
注意這里的類型是script。
【示例3-9】getScript-ajax.html
01 <! DOCTYPE HTML> 02 <html> 03 <head> 04 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> 05 <title>$.getScript()</title> 06 <script type="text/javascript" src="../jquery-3.1.1.js"></script> 07 <script type="text/javascript"> 08 function sendAjax(){ 09 $.getScript("json.js"); //調取js文件并執行 10 } 11 </script> 12 </head> 13 <body style="text-align:center"> 14 <input type="button" value="獲取JavaScript代碼" onclick="sendAjax()"/> 15 </body> 16 </html>
第09行直接獲取json.js文件,該文件的代碼為:
alert('hello external js');
本示例的效果如圖3.10所示。

圖3.10 $. getScript ()的效果
推薦閱讀
- Learning LibGDX Game Development(Second Edition)
- Python深度學習:基于TensorFlow
- PySide 6/PyQt 6快速開發與實戰
- Microsoft 365 Certified Fundamentals MS-900 Exam Guide
- Java EE企業級應用開發教程(Spring+Spring MVC+MyBatis)
- C語言從入門到精通
- Java高級程序設計
- Python滲透測試編程技術:方法與實踐(第2版)
- Python深度學習(第2版)
- Implementing Splunk(Second Edition)
- Building E-Commerce Solutions with WooCommerce(Second Edition)
- Java EE框架開發技術與案例教程
- Learning VMware vCloud Air
- Node.js入門指南
- Mastering PostCSS for Web Design