重複の可能性:
$.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: