use*_*683 6 javascript ajax json
我刚刚开始使用javascript和json.
我需要在javascript函数中处理事件时从json文件中读取数据(getInformation函数).所以我需要它是同步的.我不知道我是否遗漏了代码中的内容,或者我是否必须创建一个Request并处理回调,或者如果我需要导入其他javascript来使用json.因为我不知道如何让它发挥作用.它不起作用,因为最后数组是空的.任何帮助都是值得赞赏的.
json文件:
{"Users": [
{"Name": "Jane",
"Points": 67,
"age": 23},
{
"Name": "Sam",
"Points": 65,
"age": 21}
]}
Run Code Online (Sandbox Code Playgroud)
选项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;
}
Run Code Online (Sandbox Code Playgroud)
选项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; }
Run Code Online (Sandbox Code Playgroud)
我已经看到了以下主题并尝试了什么但是对我不起作用.我想知道我的代码中的问题在哪里或者需要任何特殊配置.
当JavaScript在浏览器中运行时,它需要向服务器发出AJAX请求以访问JSON文件.可以手动编写AJAX请求,但这在所有浏览器中都很复杂且难以实现.相反,大多数人使用像jQuery这样的库.您需要在网页中包含jQuery,例如:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" ></script>
Run Code Online (Sandbox Code Playgroud)
然后在html页面中较低的任何脚本标记中,您应该能够执行以下操作:
$.ajax({
url: "data/users.json",
dataType: "json",
success: function(response) {
$.each(response.Users, function(item) {
informationArray.push(item);
});
informationArray.push("success");
}
});
Run Code Online (Sandbox Code Playgroud)
见http://api.jquery.com/jQuery.ajax/
要加载 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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
32108 次 |
| 最近记录: |