duanjiao6730 2014-07-04 19:41
浏览 37
已采纳

试图从php获取json的实时百分比

I am trying to update on screen without refresh the current percentage that is updated into a database when the user checks something but failed to accomplish this. Problem is that in the console I get the error TypeError: a is undefined ..."resolve"],fail:[b,"reject"],progress:[c,"notify"]},function(a,b){var c=b[0],e=b and the GET request is repeated infinite. Within the get request, the response is: {"percentage":null}. An additional problem is that the GET request seams to load complete (like getting the final response) only when the php script finishes. I checked the database and every time I refresh the database dynamically I can see the percentage updating. So it's not a problem from the PHP or SQL, may be a problem from getter.php (file that is printing the result) and the json script. Please help me on this issue I checked the entire day + yesterday on how to echo value from database live and tried lots of examples but did not understood complete how to do it (this is mostly related to jquery knob, want to implement it there after success). Your help is much appreciated.

Jquery:

jQuery_1_11_0('#check').on('submit', function (e) {
    done();

    function done() {
        setTimeout(function () {
            updates();
            done();
        }, 1000);
    }

    function updates() {
        $.getJSON("lib/getter.php", function (data) {
            $("#progressbar").empty();
            $.each(data.result, function () {
                percentage = this['percentage'];
                if (percentage = null) {
                    percentage = 100;
                    $("#progressbar").html(percentage);
                }
            });
        });
    }
});

process.php

$urlsarray = array('google.com', 'yahoo.com', 'bing.com'); 
// this is a dynamic array created by the user, I am giving just a simple example
$counter = 0;
$total = count($urls1);
$session_id = rand(100000000000000, 999999999999999);
$db->query("INSERT INTO sessions (session_id, percentage) VALUES ('$session_id', '$counter')");
foreach ($urlsarray as $urls) {
    doing some things
    $counter++;
    $percentage = ($counter/$total) * 100;
    $db->query("UPDATE sessions SET percentage = '$percentage' WHERE session_id = '$session_id'");       
}
$db->query("DELETE FROM sessions WHERE session_id = '$session_id'");
$percentage = 100;

getter.php

include("process.php");
global $session_id;
$readpercentage = $db->query("SELECT percentage FROM sessions WHERE session_id = '$session_id'");
$percentage = $readpercentage->fetch_assoc();
echo json_encode(array('percentage' => $percentage));
ob_flush();
flush(); 

EDIT 2 UPDATE

function updates() {
    $.getJSON("lib/getter.html", function (data) {
        $("#progressbar").empty();
           $("#progressbar").html(data.percentage);
    });
}

EDIT 3

var myInterval = setInterval(function(){ updates(); }, 1000);
    function updates() {
        $.getJSON("lib/getter.html", function (data) {
            //$("#progressbar").empty();
            console.log(data);
            $("#progressbar").html(data.percentage);
            if(data.percentage >= 100){
                clearInterval(myInterval);
            }
        });
    }

EDIT 4. changed getter.php

include("process.php");
//global $session_id;
//echo $session_id;
$readpercentage = $db->query("SELECT percentage FROM sessions WHERE session_id = '$session_id'");
$percentage = $readpercentage->fetch_assoc();
$percentage = (int) $percentage['percentage'];
if ($percentage = 100) {
    $percentage = 100;
}
echo json_encode(array('percentage' => $percentage));
ob_flush();
flush(); 

and the js script

var jQuery_1_11_0 = $.noConflict(true);
jQuery_1_11_0('#check').on('submit', function (e) {

var myInterval = setInterval(function(){ updates(); }, 1000);
    function updates() {
        $.getJSON("lib/getter.html", function (data) {
            var percentage = data.percentage;
            $("#progressbar").html(percentage).show();
            if(percentage >= 100 || typeof percentage !== 'undefined'){
                clearInterval(myInterval);
            }
        });
    }
});
// second script is for posting the result
jQuery_1_11_0('#check').on('submit', function (e) {
    var validatef = $("#url").val();
    var validaterror = $('#errorvalidate');
    if (validatef == 'Enter Domains Separated By New Line -MAX 100 DOMAINS-') {
        validaterror.text('Please enter domain names in the text area');
        e.preventDefault();
    } else {
        validaterror.text('');
        $.ajax({
            type: 'post',
            url: 'lib/process.php',
            data: $('#check').serialize(),
            success: function (data) {
                $("#result").html(data); // apple
                // $("#progressbar").knob().hide();
            }
        });

        e.preventDefault();

    } // ending the else
});
  • 写回答

2条回答 默认 最新

  • drgm51600 2014-07-04 20:18
    关注

    I cant help but wonder:

    done();
    
    function done() {
        setTimeout(function () {
            updates();
            done();
        }, 1000);
    }
    

    How does this recursion stops? Because to me it seems like this timeout will keep on firing eternally. You really need a timeInterval here, set it to a variable, and clear the interval when 100% has been reached.

    Maybe replace the above with:

    var myInterval = setInterval(function(){
        updates();
    }, 1000);
    

    then, on the updates function

    if(percentage >= 100){
        clearInterval(myInterval);
    }
    

    By the way, doing:

    if(percentage = null){
        ...
    }
    

    Did you mean to compare using = instead of == ? If you want to verify that percentage is set and is a valid number, it would probably be a good idea to do:

    if(typeof percentage !== 'undefined' && !isNaN(parseFloat(percentage)){
        ...
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊