0

重複の可能性:
$.ajax() 関数内からの戻り値

私は、コントローラーへの広範な AJAX 呼び出しを利用する CakePHP アプリに取り組んでいます。コントローラーからの応答を JS グローバル変数に割り当てようとしている特定の AJAX 呼び出しに行き詰まっています。コードは次のとおりです。

window.errors = "";

function setErrors(err) {
    window.errors = err;
}

function ajaxCall(u, t, d, dt) {
    var type = typeof t !== 'undefined' ? t : "post";
    var dataType = typeof dt !== 'undefined' ? dt : "json";
    var success = false;
    var err = "";
    $.ajax({url: url, data: "data=" + d, type: type, dataType: dataType,
        success: function(d){
                if(d.hasOwnProperty('success') === false) { //json response
                    for(var i in d) { //fetch validation errors from object
                        for(var j in i) {
                            if(typeof d[i][j] === "undefined") {
                                continue;
                            }
                            err += d[i][j] + "<br/>";
                        }
                    }
                    console.log(err); //<=== displays correct value
                    setErrors(err); //<=== but somehow this seems to be failing??
                }
                else {
                   if(d.success === "1") {
                       success = true;
                }
            }
        }
    });
    return success; //<=== I suspect this might be the culprit
}

そして、これが ajaxCall() の使用方法です。

function register() {
    var data = {};
    var $inputs = $("#regForm :input");
    $inputs.each(function(){
        data[this.name] = $(this).val();
    });
    data = {"User" : data }; //CakePHP compatible object
    data = JSON.stringify(data);

    //Here's the AJAX call
    if(ajaxCall('https://localhost/users/add', 'post', data, 'json')) {
        alert("Registered!");
    }
    else {
        alert(window.errors); // <=== empty string
        console.log("window.errors is: " + window.errors); // <=== empty string
    }
}

ただし、Chrome JS コンソールでwindow.errorsは、正しい値 (空でない検証エラー文字列) を返します。

おそらく私の問題に対処している可能性のある同様の質問を見つけました(コールバックの前に実行されているreturn success直後)。コードを大幅に変更せずにこれを修正するにはどうすればよいですか (また、これを同期呼び出しにしたくありません)。$.ajax()success:

4

1 に答える 1

0

returnはい、成功コールバックの前にステートメントが実行されるのは正しいです。関数は成功イベントを処理する前に戻る必要があるため、関数から結果を返すことはできません。

関数にコールバックを追加しajaxCall、成功変数を設定する代わりにそれを呼び出します。

function ajaxCall(u, t, d, dt, callback) {
  var type = typeof t !== 'undefined' ? t : "post";
  var dataType = typeof dt !== 'undefined' ? dt : "json";
  $.ajax({url: url, data: "data=" + d, type: type, dataType: dataType,
    success: function(d){
      if(d.hasOwnProperty('success') === false) { //json response
        for(var i in d) { //fetch validation errors from object
          for(var j in i) {
            if(typeof d[i][j] === "undefined") {
              continue;
            }
            err += d[i][j] + "<br/>";
          }
        }
        callback(false, err);
      } else {
        callback(d.success === "1", "");
      }
    }
  });
}

ajaxCall結果を処理するためのコードを関数に送信します。

ajaxCall('https://localhost/users/add', 'post', data, 'json', function(success, err){
  if (success) {
    alert("Registered!");
  } else {
    alert(err);
  }
});
于 2012-09-03T14:44:13.690 に答える