简体   繁体   English

与Jquery同步“ Ajax”调用似乎不起作用

[英]Synchronous “Ajax” Call with Jquery does not appear to Work

I'm pretty new to javascript and I'm buiding a react/flux app and using jquery to make synchronous "ajax" calls (sjax?) to the backend. 我对javascript很陌生,正在构建一个react / flux应用程序,并使用jquery向后端进行同步的“ ajax”调用(sjax?)。 I'm getting inconsistent behavior because (I think) my ajax call is not blocking despite using async:false. 我得到不一致的行为,因为(我认为)尽管使用async:false,我的ajax调用也没有阻塞。 The key code snips are below. 关键代码片段如下。

The execution flow starts in the Flux store with the ActionTypes.LOGIN case, then moves to fetchAccount(action.value);, and should be synchronously followed by AppStore.emitChange(); 执行流程从Flux存储区以ActionTypes.LOGIN情况开始,然后移至fetchAccount(action.value);,然后应紧跟AppStore.emitChange();。

The issue is if I call AppStore.emitChange(); 问题是如果我调用AppStore.emitChange(); in my $.ajax success function then I am able to guarantee that AppStore.emitChange(); 在$ .ajax成功函数中,我就可以保证AppStore.emitChange(); come after the success function, but otherwise if AppStore.emitChange() comes after the fetchAccount(action.value) call it gets executed before the $.ajax success function completes. 在成功函数之后出现,否则,如果AppStore.emitChange()在fetchAccount(action.value)调用之后出现,它将在$ .ajax成功函数完成之前执行。

In my Flux Store, I call a helper function and then emit a change: 在我的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 ...
  }
});

My helper function executes the ajax call: 我的助手函数执行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;

    }    
  });
};

Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation. 跨域请求和dataType:“ jsonp”请求不支持同步操作。 See http://api.jquery.com/jquery.ajax/ 参见http://api.jquery.com/jquery.ajax/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM