ESP32网络服务器:ajax脚本有点无响应

时间:2018-06-13 09:24:35

标签: json ajax webserver esp32

我指的是这个话题: https://stackoverflow.com/questions/44809589/web-server-on-esp32-how-to-update-and-display-sensor-values-from-the-server-aut#=

Scandrett更新了他的代码,所以它也可以在没有有效的互联网连接的情况下工作: http://plnkr.co/edit/7DyTmdRdWSIRxx7ESLNv

我试图在网页中更新ESP32的连接状态。而不是重新加载整个页面我只想重新加载一个< h2>标签。我在上面的主题中尝试了Scandrett建议的选项2。

这是我的arduino代码:

    #include <EEPROM.h>
    #include <WiFi.h>
    #include <WiFiClient.h>
    #include <WebServer.h>
    #include <ESPmDNS.h>
    #include "webpage/webpage.h"

    #define EPR_SIZE          64
    #define EPR_SSID          0
    #define EPR_PSK           128
    #define EPR_TIME          256

    #define WIFI_ATTEMPTS     50

    enum
    {
      notConnected = 0,
      connecting,
      connectionSuccess_,
      connectionFail
    } connectionStatii;

    const char *mySsid = "Klokgebouw";
    const char *myPassword = "cooleklok";
    char *yourSsid = "";
    char *yourPassword = "";
    bool connectionSuccess = false;
    String tmp = "";

    int connectionStatus = notConnected;

    WebServer server(80);

    void setup()
    {
      Serial.begin(115200);
      Serial.println("Starting clock");

      WiFi.softAP(mySsid, myPassword);
      Serial.println("Acces point enabled.");

      server.on("/", handleRoot);
      server.on("/updateConnection", handleConnectionStatus);
      server.begin();
      Serial.println("Webserver started.");

      if(!EEPROM.begin(EPR_SIZE))
      {
        Serial.println("EEPROM failed to start.");
      }
      else
      {
        Serial.println("EEPROM Succesfully booted.");
      }
    }

    void loop()
    {
      server.handleClient();
    }

    void handleRoot()
    {
      if(server.hasArg("ssid") == true)
      {
        tmp = server.arg("ssid");
        yourSsid = new char[tmp.length() + 1];
        tmp.toCharArray(yourSsid, tmp.length() + 1);
        tmp = server.arg("password");
        yourPassword = new char[tmp.length() + 1];
        tmp.toCharArray(yourPassword, tmp.length() + 1);
        server.send(200, "text/html", WEBPAGE);
        connectionSuccess = false;
        connectionStatus = connecting;
        WiFi.begin(yourSsid, yourPassword);
        for(int i = 0; i < WIFI_ATTEMPTS; i++)
        {
          if(WiFi.status() != WL_CONNECTED)
          {
            delay(500);
          }
          else
          {
            connectionSuccess = true;
            break;
          }
        }
        if(connectionSuccess == true)
        {
          connectionStatus = connectionSuccess_;
        }
        else
        {
          connectionStatus = connectionFail;
        }
        server.send(200, "text/html", WEBPAGE);
      }
      else
      {
        server.send(200, "text/html", WEBPAGE);
      }
    }

    void handleConnectionStatus()
    {
      char msg[128];
      switch(connectionStatus)
      {
        case notConnected:
          sprintf(msg, "{\"connection\": \"%s\"}", "Connect to your WiFi");
          break;
        case connecting:
          sprintf(msg, "{\"connection\": \"%s\"}", "Connecting..");
          break;
        case connectionSuccess_:
          sprintf(msg, "{\"connection\": \"%s\"}", "Succesfully connected to your WiFi");
          break;
        case connectionFail:
          sprintf(msg, "{\"connection\": \"%s\"}", "Failed to connect to your WiFi");
          break;
        default:
          sprintf(msg, "{\"connection\": \"%s\"}", "Problem__");
          break;
      }
      server.send(200, "application/json", msg);
    }

我的网页如下:

                            <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
            <html xmlns="http://www.w3.org/1999/xhtml">
                <head>
                    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
                    <title>Login to your WiFi</title>
                </head>
                <body style="background:#FF6600;">
                    <div style="background:#fff; width:640px; margin: 0 auto;">
                        <h1 style="background-color:#FF9900; min-height: 40px;">&nbsp;</h1>
                        <form style="margin:20px 20px 0; padding:0 0 20px; font-family:Tahoma; font-size:small;" method="post" action="">
                            <div style="border-bottom:1px dotted #ccc;">
                                <h2 style="font-size:160%; font-weight:400; margin:0 0 3px;"><span id="connection"></span></h2>
                            </div>
                            <br />
                            <ul style="margin: 0; padding: 0; width: 100%;">
                                <li style="width:61%; padding:4px 5px 2px 9px; position:relative; display:block;">
                                    <label style="font-weight:700;">SSID</label>
                                    <br />
                                    <input name="ssid" type="text" maxlength="255" value=""/>
                                </li>
                                <br />
                                <li style="width:61%; padding:4px 5px 2px 9px; position:relative; display:block;">
                                    <label style="font-weight:700;">Password</label>
                                    <br />
                                    <input name="password" type="password" maxlength="255" value=""/>
                                </li>
                                <br />
                                <li style="width:61%; padding:4px 5px 2px 9px; position:relative; display:block;">
                                    <input type="submit" name="connect" value="Connect" />
                                </li>
                            </ul>
                        </form>
                    </div>
                    <script>
                        requestData();
                        setInterval(requestData, 200);
                        function requestData()
                        {
                            var xhr = new XMLHttpRequest();
                            xhr.open("GET", 'http://192.168.4.1/updateConnection', true);

                            xhr.onload = function(e)
                            {
                                if(xhr.status === 200)
                                {
                                    if(xhr.responseText)
                                    {
                                        var data = JSON.parse(xhr.responseText);

                                        document.getElementById("connection").innerText = data.connection;
                                    }
                                    else
                                    {
                                        document.getElementById("connection").innerText = "?";
                                    }
                                }
                                else
                                {
                                    console.log("Request failed");
                                    document.getElementById("connection").innerText = "Error";
                                }
                            }

                            xhr.send();
                        };
                    </script>
                </body>
            </html>

我使用这个python脚本将html文件转换为我可以与arduino一起使用的包含:

            file = open("index.html", "r")
            text = file.read()
            textLength = len(text)
            file.close()
            file = open("webpage.h", "w")
            file.write("#define WEBPAGE         \"")
            text = text.replace("\n", "\\n")
            text = text.replace("\"", "\\\"")
            file.write(text)
            file.write("\"")
            file.close()

访问192.168.4.1/updateConnection为我提供了格式良好的JSON字符串。它显示&#34;连接到您的WiFi&#34;。当我输入我的SSID和密码时,它应显示&#34;正在连接....&#34;但它并没有。然而,当它连接时,它确实显示&#34;成功连接到您的WiFi&#34;。为什么没有显示&#34;正在连接...&#34;? AJAX代码使用回调,我理解它运行客户端所以它不应该是因为arduino代码卡在handleRoot函数内。

0 个答案:

没有答案