【发布时间】:2010-11-18 20:19:18
【问题描述】:
当表单被提交时,我正在调用一个函数 getPosts 并传递一个变量 str。我想做的是获取从该函数返回的数据。
// 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(something);, 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
}
【问题讨论】:
标签: javascript jquery arrays return-value