jQuery $.ajax(),将成功数据传递给单独的函数 [英] jQuery $.ajax(), pass success data into separate function
本文介绍了jQuery $.ajax(),将成功数据传递给单独的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用 jQuery $.ajax() 函数.我已将其放入父函数中,该函数将一些值传递给 ajax 函数.我想要做的是有一个用户定义的回调函数,它获取从 ajax 成功函数传入的数据参数.
I am using the jQuery $.ajax() function. I have put this into a parent function, which passes some values into the ajax function. What I would like to do, is have a user defined callback function, which gets the data param passed in from the ajax success function.
这是我认为可行的方法,但事实并非如此:
Here is what I was thinking would work, but it is not:
testFunc = function(str, callback) {
// Send our params
var data = 'some data to send';
$.ajax({
type: 'POST',
url: 'http://www.myurl.com',
data: data,
success: callback
});
}
然后我希望能够调用该函数,并传入我的自定义函数,以便我可以使用该函数内部的成功函数数据:
Then I want to be able to call that function, and pass in my custom function so that I can use the success functions data from inside that function:
testFunc('my string data', function(data){
alert(data);
});
我希望这与:
testFunc = function(str, callback) {
// Send our params
var data = 'some data to send';
$.ajax({
type: 'POST',
url: 'http://www.myurl.com',
data: data,
success: function(data) {
alert(data);
}
});
}
推荐答案
对我来说效果很好:
<script src="/jquery.js"></script>
<script>
var callback = function(data, textStatus, xhr)
{
alert(data + " " + textStatus);
}
var test = function(str, cb) {
var data = 'Input values';
$.ajax({
type: 'post',
url: 'http://www.mydomain.com/ajaxscript',
data: data,
success: cb
});
}
test('Hello, world', callback);
</script>
这篇关于jQuery $.ajax(),将成功数据传递给单独的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文