简体   繁体   中英

ESP8266 WebServer

I found interesting code on stack overflow, but the only thing I don't like about it is that it uses JQuery that is imported via the Internet, and I need it all to work without connecting to the Internet. Can you please tell me how this can be changed?

Code:

void handleRoot() {

  snprintf ( htmlResponse, 3000,
"<!DOCTYPE html>\
<html lang=\"en\">\
  <head>\
    <meta charset=\"utf-8\">\
    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\
  </head>\
  <body>\
          <h1>Time</h1>\
          <input type='text' name='date_hh' id='date_hh' size=2 autofocus> hh \
          <div>\
          <br><button id=\"save_button\">Save</button>\
          </div>\
    <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js\"></script>\    
    <script>\
      var hh;\
      $('#save_button').click(function(e){\
        e.preventDefault();\
        hh = $('#date_hh').val();\       
        $.get('/save?hh=' + hh , function(data){\
          console.log(data);\
        });\
      });\      
    </script>\
  </body>\
</html>"); 
      server.send ( 200, "text/html", htmlResponse );  
}
void handleSave() {
  if (server.arg("hh")!= ""){
    Serial.println("Hours: " + server.arg("hh"));
}
}
void setup() {

  // Start serial
  Serial.begin(115200);
  delay(10);


  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  server.on ( "/", handleRoot );
  server.on ("/save", handleSave);

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

The minified jquery javascript can be stored on the ESP and served up by the module when the browser requests it.

One easy way to do this is to use the SPI Flash File System to serve up the HTML as well as the JQuery javascript.

This means creating an index.html in a data sub-directory in the sketch. Add the HTML in the original sketch into the file. Also change the script source in this file to a relative path:

<script src="jquery.min.js"></script>

Then download jquery.min.js and copy this into the data sub-directory as well.

The example code at https://tttapa.github.io/ESP8266/Chap11%20-%20SPIFFS.html can be used as a starting point for the rest of the code. The main parts of this involve initializing SPIFFS and setting up the handler for the file request:

SPIFFS.begin();

server.onNotFound([]() {
  if (!handleFileRead(server.uri()))
    server.send(404, "text/plain", "404: Not Found");
});

// retain the save endpoint
server.on("/save", handleSave);

server.begin();

Then implement the file handler and its content type handler:

String getContentType(String filename)
{
  if (filename.endsWith(".html")) return "text/html";
  else if (filename.endsWith(".css")) return "text/css";
  else if (filename.endsWith(".js")) return "application/javascript";
  else if (filename.endsWith(".ico")) return "image/x-icon";
  return "text/plain";
}

bool handleFileRead(String path) {
  Serial.println("handleFileRead: " + path);
  if (path.endsWith("/"))
  {
    path += "index.html";
  }

  String contentType = getContentType(path);
  if (SPIFFS.exists(path))
  {
    File file = SPIFFS.open(path, "r");
    size_t sent = server.streamFile(file, contentType);
    file.close();
    return true;
  }

  Serial.println("\tFile Not Found");
  return false;
}

Alternate Approach: Remove the JQuery dependency

An alternative approach is to rewrite the javascript so that JQuery is not required.

This involves registering an onclick handler on the button ( https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Event_handlers ), getting the value from the input field ( https://stackoverflow.com/a/11563667/1373856 ) and sending a GET request ( https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/send )

You just has to include it as script-tag with the local path on your machine.

<script src="path-to-jquery/jquery.min.js" type="text/javascript"></script>

First you have to download the needed jquery file and store it in your local path.首先,您必须下载所需的 jquery 文件并将其存储在本地路径中。 The needed path-to-jquery should than be a relative path from the html-file to the jquery.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM