2013-06-21 4 views
-1

페이지에서 jquery의 $ .post 함수를 여러 번 사용해야합니다. 또한 필터링 목적으로 post 메서드에서 반환 된 데이터를 사용해야합니다. 그래서 저는 다음과 같이 post 함수를 넣었습니다 :jquery chunk에서 함수를 실행하는 방법

$(document).ready(function(){ 
function loadData(url){ 
$.post(url,function(data){ 
var $data = data; 
}); 
} 

var raw = loadData(page01.php).filter("#someId").html(); 
$("#content").html(raw); 

var raw = loadData(page02.php).filter("#anotherId").html(); 
$("#content2").html(raw); 
}); 

그러나 작동하지 않습니다. 위의 코드를 수정하면 도움이 될 것입니다. 감사합니다

+2

의미 :

코드를 다음과 같이 보일 것인가? – j08691

+1

불완전한 질문이지만 http://stackoverflow.com/questions/12475269/variable-doesnt-get-returned-from-ajax-function (및 비슷한 것)과 중복되는 것으로 보입니다. –

+1

함수가 반환되지 않습니다. 아약스는 비동기입니다. – adeneo

답변

1

jQuery loadData('page02.php').filter처럼 함수를 마술처럼 호출하여 다른 메소드를 호출 할 수 없습니다.이 경우 함수가 jQuery 객체를 반환해야 loadData 함수가 아무 것도 반환하지 않습니다. 하지만 jQuery 객체는 aynchonous 호출이므로 반환 할 수 없습니다. 서버에서 반환 한 내용이 html 인 경우 해당 html을 수정하려면 콜백 함수를 추가해야합니다. 이는 아약스 호출 후에 무언가를 적용 할 수있는 유일한 방법이기 때문입니다.

"작동하지 않는"무엇
$(document).ready(function(){ 
    function loadData(url, callback) { 
     $.post(url, function(data){ 
      callback($(data)); // not sure if jquery detect if the content is 
           // html here, if yes then you can remove $() 
     }); 
    } 

    loadData('page01.php', function(html) { 
     var raw = html.filter("#someId").html(); 
     $("#content").html(raw); 
    }); 

    loadData('page02.php', function(html) { 
     var raw = html.filter("#anotherId").html(); 
     $("#content2").html(raw); 
    }); 
}); 
+0

일하기, 고마워. $()는 콜백에 보관해야하며 그렇지 않으면 작동하지 않습니다. – stockBoi

관련 문제