【问题标题】:jquery $.GET multiple callsjquery $.GET 多次调用
【发布时间】:2009-03-26 00:17:17
【问题描述】:

我正在学习 jquery 并写了这个,所以我可以对一个 php 文件执行两个单独的 $.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

        });


    });

有更简单的方法吗?

【问题讨论】:

    标签: php jquery ajax


    【解决方案1】:

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

    由于 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 ); 
    
    });
    

    1。好吧,您可以使用同步模式,但这很讨厌,它会停止一切

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-17
      相关资源
      最近更新 更多