如何从其他文件访问json?
我试过了:
obdatabase.json
{ "pobject" :[
{ "pname":"Pikachu" , "pid":"1" },
{ "pname":"squirtle" , "pid":"2" },
{ "pname":"Justinbieber" , "pid":"3" }
]};
test.php的
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="obdatabase.json"></script>
<script>
$(function() {
console.log(pobject);
});
</script>
答案 0 :(得分:2)
使用jQuery的getJSON()
方法:
var obj = $.getJSON( 'obdatabase.json' );
由于getJSON
会自动将结果解析为Javascript对象,因此您可以按如下方式访问属性:
// Get the object:
var db;
$.getJSON( 'obdatabase.json', function(obj) {
// Now we can access properties:
obj.pobject[0].pname; // Will be Pikachu
// Assign obj to db (so we can access it outside of the callback):
db = obj;
});