第一步:
編寫基礎的 html 框架內容,並引入 jquery:
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>測試Ajax</title> <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script> <script> </script> </head> <body> </body> </html>
第二步:
在 “<body></body>” 中間插入要點擊的按鈕和用來顯示數據的<p>標簽,並編寫對應的 function:
“ajax的使用往往配合事件操作進行調用”
<body> <button id="btn">點擊獲取數據</button> <p id="ganmao"></p> </body>
function:
<script> $(function(){ $("#btn").on("click", function(){ //調用 ajax }); }) </script>
第三步:
使用 ajax 調用后台接口並處理數據:
$.ajax({ url: 'http://localhost:53087/test/ajax', //后端程序的url地址 type: 'get', dataType: 'json', data:{ //發送給服務器的數據,如果是get請求,也可以寫在url地址的?后面 "city":'鄭州', } }) .done(function(resp){ //請求成功以后的操作(resp是后端返回的json數據,值為:{"city":"鄭州"}) console.log(resp); var data = eval('(' + resp + ')'); //data為json數據轉換成的對象,值為:{city: "鄭州"} console.log(data); var city = data['city']; console.log(city); $('#ganmao').html(city) }) .fail(function(error){ //請求失敗以后的操作 console.log(error); });
合在一起的代碼:

<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>測試Ajax</title> <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script> <script> $(function(){ $("#btn").on("click", function(){ $.ajax({ //后端程序的url地址 url: 'http://localhost:53087/test/ajax', type: 'get', dataType: 'json', data:{ //發送給服務器的數據,如果是get請求,也可以寫在url地址的?后面 "city":'鄭州', } }) .done(function(resp){ //請求成功以后的操作 console.log(resp); var data = eval('(' + resp + ')'); console.log(data); var city = data['city']; console.log(city); $('#ganmao').html(city) }) .fail(function(error){ //請求失敗以后的操作 console.log(error); }); }); }) </script> </head> <body> <button id="btn">點擊獲取數據</button> <p id="ganmao"></p> </body> </html>
運行效果:
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
PS:
過程中遇到了報錯:“Failed to load http://localhost:53087/test/ajax: No 'Access-Control-Allow-Origin’ header is present on the requested resource” 無響應解決方法。百度找到好像是跨域問題,解決方法是 在config里面加上:
<system.webServer> <httpProtocol> <customHeaders> <add name="Access-Control-Allow-Methods" value="OPTIONS,POST,GET"/> <add name="Access-Control-Allow-Headers" value="x-requested-with"/> <add name="Access-Control-Allow-Origin" value="*" />//表示允許所有來源進行跨域訪問 </customHeaders> </httpProtocol> </system.webServer>
補充學習:
前端處理 json 數據通常有3步:
1、得到 json 數據
2、解析 json 數據 (可使用 js 中的 eval 函數解析 json 數據,但要為 json 數據加上括號)
3、在頁面上顯示數據