當提交表單時,我調用一個函數getPosts並傳遞一個變量str。我想要做的是獲取從該函數返回的數據。從函數返回的訪問數組 - javascript/jquery noob moment
// when the form is submitted
$('form#getSome').submit(function(){
var str = $("form#getSome").serialize();
var something = getPosts(str);
* This is where I'd like to get the data returned from getPosts()
return false;
});
// get the data
function getPosts(str){
$.getJSON('http://myurl.com/json?'+str+'&callback=?',
function(data) {
arrPosts = new Array();
$.each(data.posts, function(i,posts){
// build array here
});
return arrPosts;
});
};
我試過很多東西,但只得到「未定義」返回。我試過console.log(某事); console.log(getPosts)。
我在這裏錯過了一些非常基本的東西。任何幫助將不勝感激。
編輯:
我試圖做的是建立一個單一的功能會得到職位。然後不同的事件會調用該函數。然後我可以使用這些數據。所以一個事件可能會提交一個表單,另一個可能會點擊一個鏈接,另一個懶惰/無盡的滾動。所有人都可以使用相同的getPosts功能。
有很多解析結果,這相當於很多代碼行。只是試圖找到一種方法來重用該功能。你認爲那可能嗎?
$('a.thisLink').click(function(){
getPosts();
get the return from getPosts() and do something with it
});
$('form.thisForm').submit(function(){
getPosts();
get the return from getPosts() and do something with it
});
function getPosts(){
get the posts and return an array
}
我認爲這是正確的軌道。我想要做的是創建一個可以獲取帖子的函數。然後不同的事件會獲得帖子。所以一個事件可能會提交一個表單,另一個可能會點擊一個鏈接,另一個懶惰的滾動。所有人都可以使用相同的getPosts功能。有很多解析結果,這相當於很多代碼行。只是試圖找到一種重用方法。你認爲那可能嗎? – jyoseph 2009-08-12 04:24:54
是的,這正是我正在尋找的,這樣我可以不斷重複使用reusableCallback函數。 最後一個問題,我如何引用在submit函數中返回的數據(來自reusableCallback函數)? – jyoseph 2009-08-12 05:00:14
@jyoseph:看看我的第二個編輯... – CMS 2009-08-12 05:39:14