0

我正在使用一些 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 网络服务器的响应是四个逗号分隔的值。

4

2 回答 2

0

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

当我对PHP文件运行Ajax请求并想要返回一个数组时,我需要将返回数据类型指定为“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,这可能没有多大帮助,但值得一试。

于 2013-05-30T17:16:34.330 回答
0

好的,看起来问题实际上已经过去了

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

论据。当我将其更改为:

{  
     if(response.readState == 4) {

我能够在 Firefox 中跳过该声明。要将状态变为 200 而不是 0,我需要修改 arduino 端的响应标头以包括:

Access-Control-Allow-Origin: *

在 FireFox 中允许跨域域请求。一旦我进行了这些更改,代码就会很好地工作,我想我用我的数组假设来找错树了。谢谢您的帮助!

于 2013-05-31T14:23:05.167 回答