Php jquery$。获取多个调用

Php jquery$。获取多个调用,php,jquery,ajax,Php,Jquery,Ajax,我正在学习jquery并编写了这篇文章,这样我就可以做两个独立的$。获取一个php文件,检索一些信息并对其进行一些计算。我知道我可以创建一个特定的php文件来执行所有操作并返回我需要的值,但我认为在需要检索信息的任何时候重用这个php文件都更有意义 我在一个函数中有这个,我不确定如何执行第一个$.GET,等待它完成,将它附加到一个变量,然后执行第二个$.GET。将变量传递给它并进行计算。相反,我把它们嵌套在一起,我认为这是不对的。这是代码 $.get("selectdb.php", {

我正在学习jquery并编写了这篇文章,这样我就可以做两个独立的$。获取一个php文件,检索一些信息并对其进行一些计算。我知道我可以创建一个特定的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

        });


    });

有更简单的方法吗?

您必须在某个级别嵌套它们

由于Ajax的异步特性(A=asynchronous),无法真正停止代码1。因此,您必须在回调中进行处理

最好的方法是实现一个在回调中调用的函数,因此它们不是嵌套的,但逻辑仍然是嵌套的

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 ); 

});

一,。可以,使用同步模式,但这很糟糕,它会停止一切,你必须在某个级别嵌套它们

由于Ajax的异步特性(A=asynchronous),无法真正停止代码1。因此,您必须在回调中进行处理

最好的方法是实现一个在回调中调用的函数,因此它们不是嵌套的,但逻辑仍然是嵌套的

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 ); 

});
一,。你可以,用同步模式,但那很糟糕,它会停止一切