doutuobao9736 2016-02-12 10:44
浏览 66
已采纳

Ajax / Jquery - 使用ajax从服务器/并行SQL查询执行返回数据时调用javascript函数

I have a PHP array of values. I loop through it, make ajax calls to the server by iterating through a for loop (I totally understand that making ajax cals in a for loop is not a great idea. Any suggestions/pointers to doing this a bette way would be awesome no doubt. I'd like to seek an answer to this question however please.). The data from the server takes different times based on what is to be processed & returned.

The problem I have is the showCustomerUsageChart function call doesn't get invoked at all at any stage. I tried debugging this by setting a breakpoint on this function's entry & see that there is no call made to it at all. However, I can see that the JSON data is being returned by the server at different points in time upon the respective data being available. I understand I've implemented this incorrectly, no doubt.

AJAX world is not all too familiar to me. I have looked up quite a few questions in this forum, but, kind of struggling to put the pieces together.

Could I request help to achieve what I'm after please. I'd be highly grateful to any help.

<script>
    var ajaxurl = 'myDbHandler.php';
    <?php for ($k = 0; $k < count($propertyCustomer); $k++) { ?>
        data = {
            'param1': paramFromUser1, 
            'param2': paramFromUser2, 
            'param3': paramFromUser3,
            'lookUpParamId': "<?php echo $k ?>"
        };

        $.post(ajaxurl, data,function (response) {
            var resp = $.parseJSON(response);
            showCustomerUsageChart(
                "<?php echo $propertyCustomer[$k][0] ?>",
                "<?php echo $propertyCustomer[$k][1] ?>",
                "<?php echo $propertyCustomer[$k][2] ?>",
                "<?php echo $propertyCustomer[$k][3] ?>",
                resp,       
            );
        });
    <?php } ?>
</script>
  • 写回答

2条回答 默认 最新

  • dongsaohu6429 2016-02-12 13:27
    关注

    So here's one way to go about it instead, I avoided using php in javascript so the code and markup are cleaner.

    To simulate the lag coming from your queries I did this:

    myDbHandler.php:

    $number = rand(2, 11);
    sleep($number);
    
    echo 'success after ' . $number . ' seconds';
    

    The original .php file now looks like this (test.php):

    <?php
    // Array filled with testdata:
    $propertyCustomer = array(
        array('value1', 'value2', 'value3', 'value4'),
        array('value1', 'value2', 'value3', 'value4'),
        array('value1', 'value2', 'value3', 'value4')
    );
    
    // Make a string that html can handle and also encode the array above to a jsonString:
    $json = htmlentities(json_encode($propertyCustomer));
    
    ?>
    
    <!-- Echo the string as data-attribute -->
    <div id="holdingElement" data-array="<?php echo $json ?>"></div>
    <script src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
    <script src="test.js"></script>
    

    I seperated js from markup, because I can't stand ugly code (test.js):

    $(document).ready(function () {
        // Get the array from the element:
        var phpArray = $('#holdingElement').data('array');
    
        // Console.log for testing:
        console.log(phpArray);
    
        // Loop through the array with the jQuery each function:
        $.each(phpArray, function(k, phpArrayValue){
            // The makeCall function returns a ajaxObject so the object gets put in var promise
            var promise = makeCall(k);
    
            // Now fill the success function in this ajaxObject (could also use .error() or .done() )
            promise.success(function(response){
                // When success, call the function and use the values out of the array above
                showCustomerUsageChart(
                    phpArrayValue[0],
                    phpArrayValue[1],
                    phpArrayValue[2],
                    phpArrayValue[3],
                    response
                );
            });
        });
    });
    
    
    
    function makeCall(paramId) {
        // Just testdata:
        var paramFromUser1 = 'val1';
        var paramFromUser2 = 'val2';
        var paramFromUser3 = 'val3';
    
        // Use ajax instead of $.post to use the success function, and return this ajaxObject
        return $.ajax({
            url: 'myDbHandler.php',
            type: 'post',
            data: {
                'param1': paramFromUser1,
                'param2': paramFromUser2,
                'param3': paramFromUser3,
                'lookUpParamId': paramId
            }
        });
    }
    
    // Function to log the results from the ajax call:
    function showCustomerUsageChart(val1, val2, val3, val4, response) {
        console.log(val1, val2, val3, val4, response);
    }
    

    I hope this makes any sence, and that it works for you!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler