好的,正在努力获得放大解码器。奇怪的问题。如果我的请求附加了 beforeSend,则解码器不会触发。删除 beforeSend 和解码器触发。
下面是两个例子。
http://jsfiddle.net/sujesharukil/Td2P4/12/
http://jsfiddle.net/sujesharukil/Td2P4/14/
有人能告诉我发生了什么吗?如果我有 beforeSend,为什么解码器不能工作?我假设解码器应该在收到请求后触发,所以 beforeSend 不应该对它产生任何影响!
注意:stackoverflow 想让我在这里发布代码,而不仅仅是 fiddle
//please check the fiddles
amplify.request({
resourceId: "testRequest",
data: {
json: JSON.stringify({
text: 'hello world'
})
},
success: function(data, status) {
console.log(data, status);
$('.messages').append('<div> text retrieved: ' + data.text + '</div>');
},
error: function(status, xhr) {
console.log(xhr);
}
});
帮助?
-苏
最佳答案
好的,想通了。 }); });
在 amplifyjs 中,这部分引起了我的注意
beforeSend : function( _xhr, _ajaxSettings ) {
xhr = _xhr;
ajaxSettings = _ajaxSettings;
var ret = defnSettings.beforeSend ?
defnSettings.beforeSend.call( this, ampXHR, ajaxSettings ) : true;
return ret && amplify.publish( "request.before.ajax",
defnSettings, settings, ajaxSettings, ampXHR );
}
});
请注意,如果指定,它将调用 beforeSend,否则将 var ret
设置为 true
如果设置为 true,它将发布 "request.before.ajax"
在文件中,放大监听此消息
amplify.subscribe( "request.before.ajax", function( resource, settings, ajaxSettings, ampXHR ) {
var _success = ampXHR.success,
_error = ampXHR.error,
decoder = $.isFunction( resource.decoder )
? resource.decoder
: resource.decoder in amplify.request.decoders
? amplify.request.decoders[ resource.decoder ]
: amplify.request.decoders._default;
if ( !decoder ) {
return;
}
function success( data, status ) {
_success( data, status );
}
function error( data, status ) {
_error( data, status );
}
ampXHR.success = function( data, status ) {
decoder( data, status, ampXHR, success, error );
};
ampXHR.error = function( data, status ) {
decoder( data, status, ampXHR, success, error );
};
所以,如果你有一个 beforeSend 并且它没有返回 true,那么消息永远不会发布并且解码器永远不会被命中!
解决方案?
从你的 beforeSend 函数返回 true
amplify.request.define("testRequest", "ajax", {
url: "/echo/json/",
dataType: 'json',
type: 'POST',
decoder: function(data, status, xhr, success, error) {
console.log('decoder fired');
$('.messages').append('<div>decoder fired </div>');
success(data);
},
beforeSend: function(xhr){
//not doing anything here, just logging;
console.log('before send fired');
$('.messages').append('<div>before send fired </div>');
return true; //this is the key
}
奇迹般有效!希望这有助于其他人试图解决这个问题!
关于jquery - amplifyjs 解码器和 ajax beforeSend,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13313439/