为什么AJAX会返回错误的结果?

时间:2016-12-25 00:15:23

标签: php jquery ajax

有时候函数reload();不会更新div的内容。单击按钮时调用此功能。有时只有一个div不会更新。随机div,随机点击。有时第一次点击不起作用。 div内容不会显示任何错误,只是之前未更新的数字。当我再次点击该按钮时,它会更新并显示正确的按钮。

错误示例(每次单击时将#number_input增加1): div内容显示: 1,2,2,4 问题在于 2s 3 缺失。在数据库中,数字是正确的。

我正在运行本地服务器(XAMPP) Firefox Chrome IE 中的问题相同。

firebug 控制台中没有错误。请求正确完成但返回值有时是错误的。通常只有一个数组项是错误的,从数据库返回的数组项。

在不同按钮上使用不同参数(完成时)的完全相同的ajax代码可以正常工作。

PS:将我的var名称更改为较短的名称,以便他们对眼睛友好

按钮HTML:

<button id="xButton" class="btn btn-info">Text</button>

按钮JS:

document.getElementById('xButton').onclick = function() {   
        var val = $('#number_input').val();
        if (val > 0) 
        {   
        var xx = 1;
        var yy = 1;
        properties(xx, yy, val); //this updates the database by current val + val. Works correctly. Values always updated, no errors there. Clean and simple code. No way this is the source of problem.

        number_input.value = 0;
        xButton.textContent = ("bla bla"); //just resets the text

        p1_reload();
        }
        } 

jQuery:

    function reload() { 
        $.ajax({ 
                type: 'POST',
                url: 'example.php',
                cache: false,
                data: {reload: "action"},
                dataType:"json",
                success: function(data) {

                var xres = new Array();
                xres = data;

document.getElementById("x1").textContent = xres[0];
document.getElementById("x2").textContent = xres[1];
document.getElementById("x3").textContent = xres[2];
document.getElementById("x4").textContent = xres[3];

//these two functions has not connection with the updated divs. They don't update or even read them. So, there shouldn't be any problems.
xFunction();
yFunction();
                }
            });
}

PHP:

if(isset($_POST['reload'])) {
    if ( $_SERVER['REQUEST_METHOD'] == 'POST' ) {

    try
        {

    require_once("session.php");
    $auth_user = new xClass();
    $user_id = $_SESSION['user_session'];


    $stmt = $auth_user->runQuery("SELECT * FROM blabla WHERE user_id=:user_id LIMIT 1");
    $stmt->execute(array(":user_id"=>$user_id));
    $userRow=$stmt->fetch(PDO::FETCH_ASSOC);


    $xxx = $userRow['xxx'];
    $yyy = $userRow['yyy'];
    $zzz = $userRow['zzz'];


    $qqq = ($xxx * $yyy) + ($zzz + $yyy + $xxx);




$xres = array();
$xres[0] = $xxx;
$xres[1] = $yyy;
$xres[2] = $zzz;
$xres[3] = $qqq;



$result = json_encode($xres);

    echo $result;

        }
        catch(PDOException $e)
        {
            echo $e->getMessage();
        }


    }
}

数据库返回简单的整数。没有触发器或十进制数字。

jQuery版本:1.12.4分钟。

每隔几秒钟点击一次(不经常点击)。请求和响应在10-38毫秒内完成。

1 个答案:

答案 0 :(得分:0)

问题出在你的按钮js以及jQuery源代码中。尝试将textContent替换为innerHTML(for plain js)html(JQuery)替换后,它将是

document.getElementById("x4").innerHTML = xres[3];或者当您使用jQuery时,您可以拥有$("#x4").html(xres[3])

相关问题