[英]Synchronous “Ajax” Call with Jquery does not appear to Work
我对javascript很陌生,正在构建一个react / flux应用程序,并使用jquery向后端进行同步的“ ajax”调用(sjax?)。 我得到不一致的行为,因为(我认为)尽管使用async:false,我的ajax调用也没有阻塞。 关键代码片段如下。
执行流程从Flux存储区以ActionTypes.LOGIN情况开始,然后移至fetchAccount(action.value);,然后应紧跟AppStore.emitChange();。
问题是如果我调用AppStore.emitChange(); 在$ .ajax成功函数中,我就可以保证AppStore.emitChange(); 在成功函数之后出现,否则,如果AppStore.emitChange()在fetchAccount(action.value)调用之后出现,它将在$ .ajax成功函数完成之前执行。
在我的Flux商店中,我调用一个辅助函数,然后发出一个更改:
// Register callback to handle all updates
AppDispatcher.register(function(action) {
var text;
switch(action.actionType) {
case ActionTypes.LOGIN:
fetchAccount(action.value);
//if i put AppStore.emitChange(); here it's invoked
//before fetchAccount completes even though the $.ajax call is async: false
AppStore.emitChange();
break;
//... code ommitted ...
}
});
我的助手函数执行ajax调用:
function fetchAccount(email) {
$.ajax({
url: "http://www.foo.com/api/accounts/" + email,
jsonp: "callback",
dataType: 'jsonp',
type: 'GET',
async: false,
headers: {"Accept" : "application/javascript; charset=utf-8"},
success: function(data) {
user = data;
currentViewState = AppStates.CONTENT_VIEW;
//AppStore.emitChange(); ---> if i emitChange here it works
},
error: function(xhr, status, err) {
user = "";
currentViewState = AppStates.LOGIN_VIEW;
}
});
};
跨域请求和dataType:“ jsonp”请求不支持同步操作。 参见http://api.jquery.com/jquery.ajax/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.