我刚刚开始使用javascript和json。
我需要在javascript函数中处理事件时从json文件中读取数据(getInformation函数)。所以我需要它是同步的。我不知道我是否遗漏了代码中的内容,或者我是否必须创建一个Request并处理回调,或者我是否需要导入其他javascript来使用json。因为我不知道如何让它发挥作用。它不起作用,因为最后数组是空的。任何帮助都是值得赞赏的。
json文件:
{"Users": [
{"Name": "Jane",
"Points": 67,
"age": 23},
{
"Name": "Sam",
"Points": 65,
"age": 21}
]}
选项1 - 正在处理事件的另一个函数调用的函数:
var getInformation = function()
{
var path = "./data/users.json";
var informationArray= [];
console.log("Loading ....");
$.getJSON(path, function(data)
{
$.each(data, function(key, val)
{
informationArray.push(key + '-' + val);
});
});
return informationArray;
}
选项2 - 由处理事件的另一个函数调用的函数:
var getInformation = function() {
var path = "./data/users.json";
var informationArray= [];
$.ajax({
url: path,
async: false,
dataType: 'json',
success: function(response) {
$.each(response.items,
function(item) {
informationArray.push(item);
});
informationArray.push("success");
}
});
return informationArray; }
我已经看过以下主题并尝试过那些但是对我不起作用。我想知道我的代码中的问题在哪里或者需要任何特殊配置。
主题:Is there a version of $getJSON that doesn't use a call back?
答案 0 :(得分:5)
当JavaScript在浏览器中运行时,它需要向服务器发出AJAX请求以访问JSON文件。可以手动编写AJAX请求,但这在所有浏览器中都很复杂且难以实现。相反,大多数人使用像jQuery这样的库。您需要在网页中包含jQuery,例如:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" ></script>
然后在html页面中较低的任何脚本标记中,您应该可以执行以下操作:
$.ajax({
url: "data/users.json",
dataType: "json",
success: function(response) {
$.each(response.Users, function(item) {
informationArray.push(item);
});
informationArray.push("success");
}
});
答案 1 :(得分:0)
要加载JSON文件(并且不需要回调),您可以使用:
var url = 'http://yoursite.com/data/users.json';
var j = [];
$.ajax({
type: 'GET',
url: url,
dataType: 'json',
success: function(data) { j = data;},
async: false
});
alert(j.Users[0].Name);