JavaScript Ajax请求无法在Firefox和Google Chrome中运行,但在Safari中可以正常使用

时间:2013-05-30 16:55:08

标签: javascript ajax arduino

我正在使用一些JavaScript向Arduino网络服务器发送Ajax请求并更改网页上的HTML

在Safari中,这一直很好用,但是当我尝试在Firefox和Google Chrome中加载它时,文档元素永远不会更新。在调试器控制台中,我可以看到请求和响应返回,所以我猜测解析数组的响应有问题吗?

以下是代码:

function GetSwitchState()
{
    nocache = "&nocache=" + Math.random() * 1000000;
    var request = new XMLHttpRequest();
    request.onreadystatechange = function()
    {
        if (this.readyState == 4)  {
            if (this.status == 200) {
                if (this.responseText != null) {
                    var response = this.responseText;
                    var comma = ",";
                    var inputArray = response.split(comma);
                    var green = inputArray[0];
                    var red = inputArray[1];
                    var fault = inputArray[2];
                    var counter = inputArray[3];
                    document.getElementById('green').innerHTML = green;
                    document.getElementById("red").innerHTML = red;
                    document.getElementById("status").innerHTML = fault;
                    document.getElementById("cars").innerHTML = counter;
                }
            }
        }
    }
    request.open("GET", "url" + nocache, true);
    request.send(null);
    setTimeout('GetSwitchState()', 1000);
}

Arduino网络服务器的响应是四个以逗号分隔的值。

2 个答案:

答案 0 :(得分:0)

我今天所做的几乎是一样的!

当我向Ajax文件运行PHP请求并希望返回一个数组时,我需要将return-datatype指定为“json”。在我的PHP文件中,然后我返回了我的值:

return json_encode(array(
    'success' => false,
    'error' => $_POST['password_hashed']
));

我正在使用jQuery来运行请求。看起来像这样:

$.ajax({
    type: 'POST',
    url: 'script.php',
    data: 'password_hashed=' + hex_sha512(str_password) + '&email=' + str_email, //Clientside password hashing
    cache: false,
    dataType: 'json',
    success: function(value){
    //Ajax successfully ran
        alert(value.success + '_' + value.error); //=false_[hash]
    },
    error: function(){
    //Ajax error occured -> Display error message in specified element
        alert('error with request');
    }
});

两天前我刚刚开始使用Ajax,这可能没有多大帮助,但值得尝试。

答案 1 :(得分:0)

好吧看起来这个问题实际上已经过了

{
            if (this.readyState == 4)  {
                if (this.status == 200) {

参数。当我把它改为:

{  
     if(response.readState == 4) {

我能够在firefox中超越该声明。要使状态为200而不是0,我需要修改arduino端的响应头以包括:

Access-Control-Allow-Origin: *

允许在FireFox中使用跨域域请求。一旦我做了这些更改,代码工作得很好,我想我正在用我的数组假设咆哮错误的树。 谢谢你的帮助!