[英]jQuery getJSON not working within a function
I'm having a problem with jQuery when using it within a selfdefined function. 在自定义函数中使用jQuery时,我遇到了问题。
When I'm starting my jQuery right from my .html like: 当我直接从我的.html启动jQuery时,例如:
<script type="text/javascript" src="js/MyJS.js"></script>
MyJS: MyJS:
$.getJSON('MyFilePath', function(data)
{
var items = [];
$.each(data, function(key, val)
{
//Doing things with my data.
});
});
it works fine and returns me my file. 它工作正常,并向我返回了我的文件。 (I'm using plain text file with a json structure).
(我正在使用具有json结构的纯文本文件)。
But when I'm trying to start it from a function eg: 但是当我尝试从一个函数启动它时,例如:
function getAllDepts()
{
$.getJSON('MyFilePath', function(data)
{
var items = [];
$.each(data, function(key, val)
{
//Doing things with my data.
});
});
}
it won't work. 它不会工作。 It seems like he's not able to load my file but I just don't get why.
看来他无法加载我的文件,但我不知道为什么。
With: 附:
$.ajax({
url: "MyFilePath",
success: function(data){
console.log(data);
},
error: function(data){
alert(error);
}
});
I'd be still able to get my data but I just want to know why getJSON doesn't work. 我仍然可以获取数据,但是我只想知道为什么getJSON不起作用。 I read that getJSON has its problems with loading local files but I'm not sure if it applies to my problem.
我读到getJSON在加载本地文件时有问题,但是我不确定它是否适用于我的问题。
Any ideas? 有任何想法吗?
@comments: @评论:
Your function doesnt look right try 您的功能看起来不正确尝试
function getAllDepts() {
$.getJSON('MyFilePath', function(data) {
var items = [];
$.each(data, function(key, val) {
//Doing things with my data.
});
});
}
Try the following. 尝试以下方法。 This may have something to do with the asynchronous nature of $.getJSON.
这可能与$ .getJSON的异步性质有关。
(document).ready(function() {
function getAllDepts()
{
$.getJSON('MyFilePath', function(data)
{
var items = [];
$.each(data, function(key, val)
{
//Doing things with my data.
});
});
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.