2009-03-26 6 views
1

나는 jquery를 배우고 이것을 썼다. 그래서 나는 PHP 파일에 2 개의 분리 된 $ .GET을 할 수 있고, 어떤 정보를 검색하고, 그것에 대한 계산을 할 수있다. 모든 것을 수행하고 필요한 값을 반환하는 하나의 특정 PHP 파일을 만들 수 있음을 이해하지만 정보를 검색해야 할 때마다이 PHP 파일을 재사용하는 것이 더 바람직하다고 생각했습니다.

함수에이 함수가 있는데 첫 번째 $ .GET을 수행하는 방법을 잘 모르겠습니다. 끝내기를 기다렸다가 변수에 연결 한 다음 두 번째 $ .GET 변수를 전달하고 계산 해. 그 대신에 내가 옳다고 생각하지 않는 것을 함께 중첩 시켰습니다. 여기에 코드가 있습니다.

$.get("selectdb.php", { 'id':nsname, 'q':'basecomplexity','table':'switchers' }, function(data) 
    { 

     $('#switchtotal'+lastIndex).html(data); //sets data to #switchtotal 

     $.get("selectdb.php", { 'id':nsname, 'q':'sources','table':'switchers' }, function(data) 
     { 
      var val1 = $('#switchtotal'+lastIndex).html(); 
      var answer = ((parseFloat(nszones)*parseFloat(data))+parseFloat(val1))*parseFloat(nsquant); 
      $('#switchtotal'+lastIndex).html(answer.toFixed(2)); //calculates formula and displays 

     }); 


    }); 

더 쉬운 방법이 있나요?

답변

1

어느 정도 수준에서 중첩해야합니다.

Ajax의 비동기 특성 (The A = Asynchronous)으로 인해 실제로 코드를 중지 할 수있는 방법이 없습니다 . 따라서 콜백에서 처리해야합니다.

당신이 얻을 수있는 최선의 방법은 콜백에서 대신 호출되는 함수를 구현하는 것입니다. 따라서 중첩되지는 않지만 논리는 여전히 중첩되어 있습니다.

jQuery(function($){ 

function dbselect(opts, callback){ 
    $.get("select.php", opts, callback); 
} 

function handle_sources(data){ 
    var val1 = $('#switchtotal'+lastIndex).html(); 
    var answer = ((parseFloat(nszones)*parseFloat(data))+parseFloat(val1))*parseFloat(nsquant); 
    $('#switchtotal'+lastIndex).html(answer.toFixed(2)); //calculates formula and displays 
} 
function handle_basecomplex (data){ 
    $('#switchtotal'+lastIndex).html(data); //sets data to #switchtotal 
    dbselect({ 'id':nsname, 'q':'sources','table':'switchers' } , handle_sources); 
} 

dbselect({ 'id':nsname, 'q':'basecomplexity','table':'switchers' }, handle_basecomplex); 

}); 

잘 동기 모드, 수 1,하지만 그 말씨, 그것은 모든

중지