溫馨提示×

json怎么與ajax結合使用

小億
99
2024-06-07 16:08:20
欄目: 編程語言

要將 JSON 和 AJAX 結合使用,可以通過 AJAX 請求從服務器獲取 JSON 數據,并在頁面上動態顯示該數據。下面是一個簡單的示例代碼:

  1. HTML 頁面代碼:
<!DOCTYPE html>
<html>
<head>
  <title>JSON and AJAX Example</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
  <h1>JSON and AJAX Example</h1>
  <button id="getDataBtn">Get Data</button>
  <div id="dataContainer"></div>
  <script src="script.js"></script>
</body>
</html>
  1. JavaScript 文件 script.js:
$(document).ready(function() {
  $('#getDataBtn').click(function() {
    $.ajax({
      url: 'data.json',
      type: 'GET',
      dataType: 'json',
      success: function(data) {
        $('#dataContainer').empty();
        $.each(data, function(key, value) {
          $('#dataContainer').append('<p>' + key + ': ' + value + '</p>');
        });
      },
      error: function() {
        alert('Error loading data');
      }
    });
  });
});
  1. JSON 數據文件 data.json:
{
  "name": "John",
  "age": 30,
  "city": "New York"
}

在這個示例中,當用戶點擊按鈕“Get Data”時,會發起一個 AJAX 請求獲取 data.json 文件中的 JSON 數據,并將其動態顯示在頁面上。

請確保您的服務器支持 AJAX 請求,并且 data.json 文件位于正確的路徑下。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女