我必须从位于项目中的文件夹中读取JSON文件。
我使用以下代码:
var obj = "www/places.json";
如何使用Javascript读取iPhone PhoneGap中项目文件夹www
中的JSON文件?
答案 0 :(得分:14)
您可以像在服务器上一样阅读它。
如果jQuery使用不是问题,那么就像这样使用它:
//Load categories object JSON
jQuery.getJSON("categories.json", function(data){
// data is yours parsed object
});
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no"/>
<script src="http://www.fajrunt.org/js/jquery-1.9.1.min.js"></script>
<title>Read JSON Demo</title>
<script>
jQuery.getJSON("categories.json", function(data){
alert(data.balance);
});
</script>
</head>
<body>
Read JSON Demo
</body>
</html>
JSON文件:
{"balance":1000.21,"num":100,"nickname":null,"is_vip":true,"name":"foo"}
如果您只想使用vanilla javascript,那么这是一个适合您的解决方案
var xmlhttp;
var jsonObject;
// code for IE7+, Firefox, Chrome, Opera, Safari
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
// code for IE6, IE5
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
jsonObject = JSON.parse(xmlhttp.responseText);
alert(jsonObject.balance);
}
}
xmlhttp.open("GET","categories.json",true);
xmlhttp.send();
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no"/>
<title>Read JSON Demo</title>
<script>
var xmlhttp;
var jsonObject;
// code for IE7+, Firefox, Chrome, Opera, Safari
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
// code for IE6, IE5
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
jsonObject = JSON.parse(xmlhttp.responseText);
alert(jsonObject.balance);
}
}
xmlhttp.open("GET","categories.json",true);
xmlhttp.send();
</script>
</head>
<body>
Read JSON Demo
</body>
</html>
JSON文件:
{"balance":1000.21,"num":100,"nickname":null,"is_vip":true,"name":"foo"}
答案 1 :(得分:0)
我遇到了同样的问题并完成了以下片段:
dojo.ready(函数(){
var xhrArgs = { url: "file:///Users/Desktop/configJSON.txt", handleAs: "json", load: function(data){ targetNode.innerHTML = data; // Your data from JSON alert("Name : "+data.fields[0].name+" Type : "+data.fields[0].type+" Alias : "+data.fields[0].alias +" Editable : "+data.fields[0].editable); }, error: function(error){ // targetNode.innerHTML = "An unexpected error occurred: " + error; alert("An unexpected error occurred: " + error); } } // Call the asynchronous xhrGet var deferred = dojo.xhrGet(xhrArgs); }); </script>
</head>
<body>
<div id="licenseContainer"></div>
<body>