jQuery getJSON在函数中不起作用 [英] jQuery getJSON not working within a function
问题描述
我在自定义函数中使用jQuery时遇到问题。
I'm having a problem with jQuery when using it within a selfdefined function.
当我从我的.html开始我的jQuery时:
When I'm starting my jQuery right from my .html like:
<script type="text/javascript" src="js/MyJS.js"></script>
MyJS:
$.getJSON('MyFilePath', function(data)
{
var items = [];
$.each(data, function(key, val)
{
//Doing things with my data.
});
});
它工作正常并返回我的文件。 (我使用的是带有json结构的纯文本文件)。
it works fine and returns me my file. (I'm using plain text file with a json structure).
但是当我试图从一个函数启动它时,例如:
But when I'm trying to start it from a function e.g.:
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.
使用:
$.ajax({
url: "MyFilePath",
success: function(data){
console.log(data);
},
error: function(data){
alert(error);
}
});
我仍然可以获取我的数据,但我只是想知道为什么getJSON没有工作。
我读到getJSON有加载本地文件的问题,但我不确定它是否适用于我的问题。
I'd be still able to get my data but I just want to know why getJSON doesn't work. I read that getJSON has its problems with loading local files but I'm not sure if it applies to my problem.
有什么想法吗?
@comments:
@comments:
- 是的我通过onclick调用该函数:getDepts( )在我的.hmtl中,它被正确调用。
- 返回值是一步,因为getJSON无法正常工作。这不是mit jQuery认为的问题,因为在使用Firebug(Firefox)进行调试时,该方法会被调用。主要问题似乎是他无法加载文件。
- 我的数据文件是.txt。与json结构。 (我用 http://jsonlint.com/ 检查了我的json结构,它说没关系)
- 没有类似404的错误,因为文件存储在本地并且在使用firebug时没有出现错误。
- 我在编辑这篇文章时创建了语法错误。修正了大括号。
- Yes I'm calling the function through an onclick:"getDepts()" in my .hmtl and it gets called correctly.
- The return value is one step ahead because the getJSON is not working correctly. It's not a problem mit jQuery thought, since when debugging with Firebug(Firefox) the method gets called. The main problem seems to be he's not able to load the file.
- My data file is an .txt. with json structure. (I checked my json structure with http://jsonlint.com/ and it said its okay)
- There's no error like 404 since the files are stored locally and no errors show up while using firebug.
- I created the syntax error while editing this post. Fixed the braces.
推荐答案
你的功能看起来不对尝试
Your function doesnt look right try
function getAllDepts() {
$.getJSON('MyFilePath', function(data) {
var items = [];
$.each(data, function(key, val) {
//Doing things with my data.
});
});
}
这篇关于jQuery getJSON在函数中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!