ajax请求本地数据
时间: 2023-12-13 07:33:53 浏览: 30
以下是使用jQuery和Ajax请求本地数据的示例代码:
```javascript
// HTML代码
<div id="product-list"></div>
// JavaScript代码
$(document).ready(function() {
$.ajax({
url: "products.json", // 本地数据文件的路径
type: "GET", // 请求类型为GET
dataType: "json", // 数据类型为json
success: function(data) {
// 请求成功时执行的回调函数
var productList = $("#product-list");
$.each(data, function(index, product) {
// 遍历数据并将其添加到页面中
productList.append("<div><a href='product.html?id=" + product.id + "'>" + product.name + "</a></div>");
});
},
error: function(jqXHR, textStatus, errorThrown) {
// 请求失败时执行的回调函数
console.log("Error: " + textStatus + " - " + errorThrown);
}
});
});
```
上述代码通过Ajax请求获取本地的JSON数据文件,并将其中的商品列表添加到页面中。其中,`url`属性指定了数据文件的路径,`type`属性指定了请求类型为GET,`dataType`属性指定了数据类型为json。请求成功时,会执行`success`回调函数,将商品列表添加到页面中;请求失败时,会执行`error`回调函数,输出错误信息。