XMLHttpRequest有时不发送字符串

时间:2014-08-11 21:00:18

标签: javascript php xmlhttprequest

我不确定为什么会这样,但我会尽量解释我已经知道的事情。 我有一个网站,允许您使用存储在数据库中的帐户登录。每个用户都可以更新同样位于同一数据库中的数据集。 当用户更改数据时,Javascript会将XMLHttpRequest发布到服务器上的php文件中。数据是JSON编码的,并在php文件中解码,然后将数据存储在数据库中。

问题是每当我登录特定帐户时,都不会发送任何数据。发送请求后,该字符串为空。帖子工作和php文件运行但没有数据存在。这是我在JS中发送请求的代码:

function sendXMLHttpRequest(data, phpfile){

    var xhr;

    if (window.XMLHttpRequest) {
        xhr = new XMLHttpRequest();
    }
    else if (window.ActiveXObject) {
        xhr = new ActiveXObject("Msxml2.XMLHTTP");
    }
    else {
        throw new Error("Ajax is not supported by this browser");
    }

    xhr.open('POST', phpfile, true);
    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            if (xhr.status === 200) {

                if (this.responseText !== null)
                    document.getElementById('saveresponse').innerHTML = xhr.responseText;
                else
                    alert("Ajax error: No data received");
            }else alert("Ajax error: " + this.status);
        }
    };

    xhr.send(data);

}

在php方面:

session_start();

$mysql = new Mysql();

$data = json_decode($_POST['stringData']);
echo 'Data: ' . $data . "<br />";

通常当我回显数据时返回Array这是我想要的但是当我登录这个特定帐户时它没有回应任何东西,发送的数据只是一个字符串{{ 1}}是一个JSON。有没有办法看看是否存储了任何东西?如果没有发送任何内容,为什么会这样呢?对我的代码有任何建议吗?

1 个答案:

答案 0 :(得分:1)

确保通过添加随机参数来缓存请求:

querystring = 'validate=' + validate+ "&rand=" + new Date().getTime();
相关问题