(jquery) ajax 호출을 통해 일부 데이터베이스 정보를 검색 한 다음 데이터를 조작하고 다양한 자바 스크립트 함수를 통해 페이지에 표시하는 웹 페이지를 개발 중입니다. 전역 패턴을 피하고 다양한 함수에 의해 데이터를 사용하기 위해 모듈 패턴 (아래의 코드 예제에서 'userapp')을 사용합니다.(jquery) ajax 호출 내에서 많은 중첩 된 함수를 방지하는 방법?
아래의 간단한 코드가 작동하지만 아약스 호출 내에서 모든 함수 (예 : test()를 아래 코드에 포함)가 포함 된 경우에만 해당 코드가 복잡해집니다. 내가 웹에서 읽은 최고의 자바 스크립트 관행). ajax 호출 (init()에 임베드 됨) 외부/예제 함수 test()를 호출하려고하면 ajax 호출이 변수 ('products []') 설정을 완료하지 않았다고 생각하여 test()가 작동하지 않습니다. 예) 아직 없습니다.
내 질문 : 아약스 호출 외에 다른 함수를 호출 할 수 있습니까? 그렇다면 어떻게해야합니까? 나는 콜백 예제를 보았다하지만 ... 그건 내 문제를 해결할 방법/여부를 확실하지 않다
단순화 된 코드 :
userapp = function(){
//userapp properties
var today = new Date();
var products = [];
var copyItems = function(source_items, target_items){
//do something
};//var copyItems
var init = function(){
$.ajax({
url: "user_admin_get.php",
data: { command: "getuserbaseinfo", val1: "", val2: "" },
success: function (msg) {
copyItems(msg.eproducts,products); //set values for 'products' used by test()
test(); //calling test() here works as the the values has been set()
},//success: function(msg)
error: function(msg) {
console.log('error result from php file:');
},//error:
dataType: "json"
});//$.ajax({
};//var init = function(){
var test = function(){
//do something
};//test()
return{init:init, test:test} //return (only) public functions and vars
}(); //userapp()
//main function document ready
$(document).ready(function(){
userapp.init();
//userapp.test(); //test() is not working here as init() has not set the requirement parameters tey
}); //$(document).ready
'init'의 이름을'ready'로 바꿀 수도 있습니다 – acoiro
thnx, 작동합니다! – Joppo