使用javascript访问本地json数据
我正在测试一个web应用程序,试图学习在jquery mobile中使用json数据。在原始应用程序中,json数据在javascript文件中显式列出。我提取了数据并将其保存在本地驱动器的一个目录中(与html文件和javascript文件位于同一位置)。更改后,由于文件访问问题,页面停止工作。我在谷歌搜索了一整天,但没有找到解决办法 HTML文件:使用javascript访问本地json数据,javascript,json,jquery-mobile,Javascript,Json,Jquery Mobile,我正在测试一个web应用程序,试图学习在jquery mobile中使用json数据。在原始应用程序中,json数据在javascript文件中显式列出。我提取了数据并将其保存在本地驱动器的一个目录中(与html文件和javascript文件位于同一位置)。更改后,由于文件访问问题,页面停止工作。我在谷歌搜索了一整天,但没有找到解决办法 HTML文件: <!DOCTYPE html> <html> <head> <meta name=viewport c
<!DOCTYPE html>
<html>
<head>
<meta name=viewport content="user-scalable=no,width=device-width" />
<title>Test data listview</title>
<link rel="stylesheet" href="../download18Dec13/jquery.mobile-1.3.2.min.css" />
<script src="../download18Dec13/jquery-1.9.1.min.js"></script>
<script src="../download18Dec13/jquery.mobile-1.3.2.min.js"></script>
<script src="test.js"></script>
<link rel="stylesheet" href="test.css"/>
</head>
<!--first page -->
<div data-role="page" id="info-page">
<div data-role="header" data-theme="b">
<h1> Information</h1>
</div>
<div data-role="content">
<ul data-role="listview" id="prof-list" data-divider-theme="a" data- inset="true">
<li data-role="list-divider" data-theme="b" role="heading">Names</li>
</ul>
</div>
</div>
<!--second page -->
<div data-role="page" id="details-page">
<div data-role="header" data-theme="b"><a href="#" data-rel="back" data- role="button">Go back</a>
<h1>Employee Details</h1>
</div>
<div data-role="content"></div>
</div>
</html>
测试数据列表视图
问询处
- 名称
员工详细信息
Javascript文件:
//assuming this comes from an ajax call
//alert(window.location.href);
response.setHeader("Access-Control-Allow-Origin", "data.js");
var info=$.getJSON('data.js',function(data){
//alert( "JSON Data: " + data[ 3 ].name );
//var info=data;
});
//var info=data;
//.done(function() {
//alert( "second success" );
//})
//.fail(function() {
//alert( "error" );
//})
//.always(function() {
//alert( "complete" );
//});
//alert(info.always());
//alert($.document.url());
//pageinit event for first page
//triggers only once
//write all your on-load functions and event handlers pertaining to page1
//var info = new Spry.Data.JSONDataSet("data.js");
//alert(infor[3].name);
//alert("ffff");
$(document).on("pageinit", "#info-page", function () {
//set up string for adding <li/>
var li = "";
//container for $li to be added
$.each(info, function (i, name) {
//add the <li> to "li" variable
//note the use of += in the variable
//meaning I'm adding to the existing data. not replacing it.
//store index value in array as id of the <a> tag
li += '<li><a href="#" id="' + i + '" class="info-go">' + name.name + '</a> </li>';
});
//append list to ul
$("#prof-list").append(li).promise().done(function () {
//wait for append to finish - thats why you use a promise()
//done() will run after append is done
//add the click event for the redirection to happen to #details-page
$(this).on("click", ".info-go", function (e) {
e.preventDefault();
//store the information in the next page's data
$("#details-page").data("info", info[this.id]);
//change the page # to second page.
//Now the URL in the address bar will read index.html#details-page
//where #details-page is the "id" of the second page
//we're gonna redirect to that now using changePage() method
$.mobile.changePage("#details-page");
});
//refresh list to enhance its styling.
$(this).listview("refresh");
});
});
//use pagebeforeshow
//DONT USE PAGEINIT!
//the reason is you want this to happen every single time
//pageinit will happen only once
$(document).on("pagebeforeshow", "#details-page", function () {
//get from data - you put this here when the "a" wa clicked in the previous page
var info = $(this).data("info");
//string to put HTML in
var info_view = "";
//use for..in to iterate through object
for (var key in info) {
//Im using grid layout here.
//use any kind of layout you want.
//key is the key of the property in the object
//if obj = {name: 'k'}
//key = name, value = k
info_view += '<div class="ui-grid-a"><div class="ui-block-a"><div class="ui-bar field" style="font-weight : bold; text-align: left;">' + key + '</div></div><div class="ui- block-b">
<div class="ui-bar value" style="width : 75%">' + info[key] + '</div></div></div>';
}
//add this to html
$(this).find("[data-role=content]").html(info_view);
});
Json data (To save space, only three items listed):
{
{
"id": 0,
"age": 31,
"name": "Avis Greene",
"gender": "female",
"company": "Handshake",
"email": "avisgreene@handshake.com",
"phone": "+1 (845) 575-2978",
"address": "518 Forrest Street, Washington, New York, 3579"
}, {
"id": 1,
"age": 31,
"name": "Dunn Haynes",
"gender": "male",
"company": "Signity",
"email": "dunnhaynes@signity.com",
"phone": "+1 (829) 454-3806",
"address": "293 Dean Street, Dante, Oregon, 5864"
}, {
"id": 2,
"age": 20,
"name": "Contreras Keith",
"gender": "male",
"company": "Overfork",
"email": "contreraskeith@overfork.com",
"phone": "+1 (941) 412-2874",
"address": "166 Broome Street, Norris, Kentucky, 2163"
}, {
"id": 3,
"age": 27,
"name": "Hays Schneider",
"gender": "male",
"company": "Orbean",
"email": "haysschneider@orbean.com",
"phone": "+1 (896) 599-2026",
"address": "889 Engert Avenue, Staples, Illinois, 9927"
}
}
//假设这来自一个ajax调用
//警报(window.location.href);
setHeader(“访问控制允许来源”,“data.js”);
var info=$.getJSON('data.js',函数(数据){
//警报(“JSON数据:”+数据[3]。名称);
//var信息=数据;
});
//var信息=数据;
//.done(函数(){
//警惕(“第二次成功”);
//})
//.fail(函数(){
//警报(“错误”);
//})
//.always(函数(){
//警报(“完成”);
//});
//警报(信息总是());
//警报($.document.url());
//第一页的pageinit事件
//只触发一次
//编写与page1相关的所有加载函数和事件处理程序
//var info=new Spry.Data.JSONDataSet(“Data.js”);
//警报(infor[3].name);
//警报(“ffff”);
$(文档)。在(“pageinit”,“信息页”,函数(){
//设置用于添加的字符串
var li=“”;
//添加$li的容器
$。每个(信息、功能(i、名称){
//将添加到“li”变量
//注意在变量中使用+=
//这意味着我正在添加现有数据,而不是替换它。
//在数组中存储索引值作为 的id;
});
//将列表附加到ul
$(“#prof list”).append(li).promise().done(函数(){
//等待append完成-这就是为什么使用promise()的原因
//完成追加后,将运行done()
//添加重定向发生在#详细信息页面的单击事件
$(此).on(单击“,”.info go“,函数(e){
e、 预防默认值();
//将信息存储在下一页的数据中
$(“#详细信息页”).data(“info”,info[this.id]);
//将页面更改为第二页。
//现在地址栏中的URL将读取index.html#details页面
//其中#details page是第二页的“id”
//我们现在将使用changePage()方法重定向到这个
$.mobile.changePage(“详细信息页”);
});
//刷新列表以增强其样式。
$(此).listview(“刷新”);
});
});
//使用pagebeforeshow
//不要使用PAGEINIT!
//原因是你希望这种情况每次都发生
//pageinit只会发生一次
$(文档)。在(“pagebeforeshow”中的“#详细信息页”,函数(){
//从数据中获取-在上一页单击“a”按钮时,您将其放在此处
var info=$(this.data(“info”);
//要放入HTML的字符串
var info_view=“”;
//用于..在中遍历对象
用于(var输入信息){
//我在这里使用网格布局。
//使用任何你想要的布局。
//key是对象中属性的键
//如果obj={name:'k'}
//key=name,value=k
信息视图+=''+键+'
“+信息[键]+”;
}
//将此添加到html
$(this.find(“[datarole=content]”)html(info\u视图);
});
Json数据(为了节省空间,仅列出三项):
{
{
“id”:0,
“年龄”:31岁,
“姓名”:“阿维斯·格林”,
“性别”:“女性”,
“公司”:“握手”,
“电子邮件”:avisgreene@handshake.com",
“电话”:“+1(845)575-2978”,
地址:“纽约州华盛顿市福勒斯特街518号,邮编3579”
}, {
“id”:1,
“年龄”:31岁,
“姓名”:“Dunn Haynes”,
“性别”:“男性”,
“公司”:“重要”,
“电子邮件”:dunnhaynes@signity.com",
“电话”:“+1(829)454-3806”,
地址:“俄勒冈州但丁市迪安街293号,邮编5864”
}, {
“id”:2,
“年龄”:20岁,
“姓名”:“Contreras Keith”,
“性别”:“男性”,
“公司”:“Overfork”,
“电子邮件”:contreraskeith@overfork.com",
“电话”:“+1(941)412-2874”,
地址:“肯塔基州诺里斯布鲁姆街166号,邮编2163”
}, {
“id”:3,
“年龄”:27岁,
“姓名”:“海斯·施耐德”,
“性别”:“男性”,
“公司”:“Orbean”,
“电子邮件”:haysschneider@orbean.com",
“电话”:“+1(896)599-2026”,
地址:“伊利诺伊州斯台普斯市恩格特大道889号,邮编9927”
}
}
这不是JavaScript问题,也不是JSON问题。这是一个浏览器安全问题 长话短说,您希望在计算机/设备上运行网页(即:直接从驱动器到浏览器),然后从该文件到硬盘进行AJAX调用以获取JSON 浏览器制造商认为这将是一个非常糟糕的主意,允许您继续这样做。
道理很简单。。。如果任何人都可以在你的系统上运行一个.html文件,那么它要求的任何JS都可以访问你计算机上的任何文件,并将数据发送给任何一个用户
{
"data":[{
"id": 0,
"age": 31,
"name": "Avis Greene",
"gender": "female",
"company": "Handshake",
"email": "avisgreene@handshake.com",
"phone": "+1 (845) 575-2978",
"address": "518 Forrest Street, Washington, New York, 3579"
}, {
"id": 1,
"age": 31,
"name": "Dunn Haynes",
"gender": "male",
"company": "Signity",
"email": "dunnhaynes@signity.com",
"phone": "+1 (829) 454-3806",
"address": "293 Dean Street, Dante, Oregon, 5864"
}, {
"id": 2,
"age": 20,
"name": "Contreras Keith",
"gender": "male",
"company": "Overfork",
"email": "contreraskeith@overfork.com",
"phone": "+1 (941) 412-2874",
"address": "166 Broome Street, Norris, Kentucky, 2163"
}, {
"id": 3,
"age": 27,
"name": "Hays Schneider",
"gender": "male",
"company": "Orbean",
"email": "haysschneider@orbean.com",
"phone": "+1 (896) 599-2026",
"address": "889 Engert Avenue, Staples, Illinois, 9927"
}]
}
<script>
$(document).on("pageinit", "#info-page", function () {
var li = '<li data-role="list-divider" data-theme="b" role="heading">Names</li>';
$.getJSON("data.json", function (json, status){
var data = json.data;
$.each(data, function(key, value){
$.each(value, function(key, value){
if(key == 'name'){
li += '<li><a href="#" id="' + key + '" class="info-go">' + value + '</a> </li>';
}
})
})
$("#prof-list").append(li).trigger('create');
$("#prof-list").listview('refresh');
})
.success(function(result) {})
.fail(function(jqXHR, textStatus, errorThrown) {})
.complete(function() {});
})
</script>