콜백 함수에 상수 값을 전달하는 데 문제가 있습니다. 나는 다음 오류 및 성공의 첫 번째 인수 (성공 또는 오류)와 같은 일정한 삽입하는 콜백 데이터를 반환하여 이벤트를 처리, ajax
를 사용하여 편안하고 요청을 수행하고, 그에게 또 다른 콜백 리스너를 반환하고 . 유일한 문제는 이러한 새로 추가 된 첫 번째 인수가 올바르게 추가되지 않는다는 것입니다. 내 오류가있는 코드에 메모를 추가했습니다. Here is the fiddle.JavaScript 콜백 값이 올바르게 전달되지 않았습니다.
(function(REST, $, undefined)
{
REST.get = function(_url, _data, _onSuccessCallback, _onErrorCallback)
{
console.log("GET");
$.ajax({
type: 'GET',
url: _url,
data: _data,
dataType: 'json',
headers: {contentType: 'application/json'},
success: _onSuccessCallback,
error: _onErrorCallback
});
};
}
(window.REST = window.REST || {}, jQuery));
(function(DSP, $, undefined)
{
var baseURL = "www.example.com";
/** The request was successful */
DSP.SUCCESS = 0;
/** The request failed */
DSP.ERROR = 1;
DSP.get = function(url, _data, callback)
{
REST.get(url,
_data,
function(data, text)
{
console.log("Success. arg0 = " + DSP.SUCCESS);
callback.call(DSP.SUCCESS, data, text);
},
function(request, status, error)
{
//So far, it's just errors.
console.log("\nError. arg0 = " + DSP.ERROR);//This prints "Error. arg0 = 1"
for (var i = 0; i < arguments.length; i++)
{
console.log(arguments[i]);//prints the request Object and the text "error"
}
callback.call(DSP.ERROR, request, status, error);//doesn't seem to correctly insert the ERROR constant.
}
);
};
DSP.getSomething = function(callback)
{
console.log("Get something");
var url = baseURL + "/Something";
DSP.get(url, null, function(){
console.log("ARGUMENTS LENGTH = " + arguments.length);//prints 3
for (var i = 0; i < arguments.length; i++)
{
console.log(arguments[i].toString());//prints all same Objects as above
}
if (arguments.length < 1) {
console.error("error in request");
callback.call(null);
}
if (arguments[0] == DSP.ERROR)//should get to here. Why doesn't it???
{
var request = arguments[1];
var status = arguments[2];
var error = arguments[3];
console.error("Failed To Get Something (" + request.responseText + ")");
callback.call(null);
}
else if (arguments[0] == DSP.SUCCESS)
{
var data = arguments[1];
var text = arguments[2];
callback.call(data);
}
else
{
//gets to this line and prints "arguments[0] ([object Object]) != SUCCESS(0) !=ERROR(1)."
console.log("arguments[0] (" + arguments[0].toString() + ") != SUCCESS(" + DSP.SUCCESS + ") != ERROR(" + DSP.ERROR + ").");
console.error("internal error");
callback.call(null);
}
});
};
}
(window.DSP = window.DSP || {}, jQuery));
window.DSP.getSomething(function(response){
if (!response)
{
//this is printed.
console.log("error. No user returned.")
}
else
{
console.log("RESPONSE: " + response.toString());
}
});
내가 뭘 잘못하고 있니? REST
의 오류로 인해 DSP.get
은 DSP.ERROR
매개 변수를 첫 번째 인수로 배치해야하며 getSomething
으로 처리해야합니다.
고마워요! 이것은 쓸모없는 디버깅을 많이 절약 해줍니다! – Phil
@ Phil : 천만에. –