[英]jQuery getJSON not working within a function
在自定義函數中使用jQuery時,我遇到了問題。
當我直接從我的.html啟動jQuery時,例如:
<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結構的純文本文件)。
但是當我嘗試從一個函數啟動它時,例如:
function getAllDepts()
{
$.getJSON('MyFilePath', function(data)
{
var items = [];
$.each(data, function(key, val)
{
//Doing things with my data.
});
});
}
它不會工作。 看來他無法加載我的文件,但我不知道為什么。
附:
$.ajax({
url: "MyFilePath",
success: function(data){
console.log(data);
},
error: function(data){
alert(error);
}
});
我仍然可以獲取數據,但是我只想知道為什么getJSON不起作用。 我讀到getJSON在加載本地文件時有問題,但是我不確定它是否適用於我的問題。
有任何想法嗎?
@評論:
您的功能看起來不正確嘗試
function getAllDepts() {
$.getJSON('MyFilePath', function(data) {
var items = [];
$.each(data, function(key, val) {
//Doing things with my data.
});
});
}
嘗試以下方法。 這可能與$ .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.