我正在尝试将Ajax请求的结果传递给触发函数。但我的回答是“在途中迷路了”......
这就是我正在做的事情:
some = function (){
// inside some function - this will call getItems()
content = $.parseJSON( dynoData[ dyn.method ]() );
};
...
dynoData = {
getItems : function(){
var form = "",
service = "../services/pull_items.cfc",
method = "process",
returnformat = "JSON",
targetUrl = "",
formdata = "form=getItems&method="+method+"&returnformat="+returnformat,
successHandler = function(objResponse) {
// here is the objResponse I need to pass back
console.log( objResponse );
return ( objResponse );
};
ajaxFormSubmit( form,
service,
formdata,
targetUrl,
successHandler,
"yes",
"",
returnformat,
"" );
}
ajaxFormSubmit = function ( form,
service,
formdata,
targetUrl,
successHandler,
dataHandler,
errorHandler,
returnformat,
type ){
$.ajax({
async: false,
type: type == "" ? "get" : type,
url: service,
data: formdata,
dataType: returnformat,
success: function( objResponse ){
if (objResponse.SUCCESS == true ||
typeof objResponse == "string" ){
dataHandler == "yes" ?
successHandler( objResponse ) : successHandler();
}
},
error: function () {}
});
}
一切正常,但我不知道如何通过getItems函数将Ajax successhandler中的objRespone
传递回调用函数。
问题:
谁能给我一个提示?
谢谢!
修改
像这样工作:
// inside some function
var content,
cbk = function(objResponse){
content = objResponse;
};
// get dynamic data
$.parseJSON( dynoData[ dyn.method ](cbk) );
console.log( content );
}
// inside getItems
getRetailers : function(cbk){
...
successHandler = function(objResponse, cbk) {
cbk( objResponse );
};
ajaxFormSubmit( form, service, formdata, targetUrl, successHandler, "yes", "", returnformat, cbk )
}
所以我在hijqcking我的最后一个参数传递cbk
而不是get/post
var ajaxFormSubmit =
function ( form, service, formdata, targetUrl, successHandler, dataHandler, errorHandler, returnformat, type ){
// cleanup
var override = null;
if ( type !== "" && type !== "post" ){
override = type;
type = "get";
}
... inside AJAX Successhandler
dataHandler == "yes" ? successHandler( objResponse, override ) : successHandler( override )
因此,如果传递了get / post,则override将为null。似乎工作正常。
答案 0 :(得分:1)
由于您的ajax调用是异步的,getItems
函数的执行将在您获取数据之前很久就完成。你可以做的一件事是为调用添加一个回调参数,并在你的ajax成功时调用它。类似的东西:
getItems: function(cbk)
//(...)
successHandler = function(objResponse) {
// here is the objResponse I need to pass back
cbk(ojbResponse);
};
但是,您必须将dynoData
调用更改为getItems
以添加回调,这将完成新对象的设置。
另一种解决方案是使ajax调用同步,但这会暂停浏览器,直到您恢复数据,这会使系统无响应。