ESP8266 Arduni IDE - AJAX ввод значений без перезагрузки страницы
- Войдите на сайт для отправки комментариев
Втр, 10/03/2020 - 14:55
Накопал в интернетах пример работы кнопок без перезагрузки страницы:
Файл ajax.ino
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include "index.h" // Содержимое нашей HTML-страницы с javascripts
const char * ssid = "f99";
const char * password = "ff4466nn";
ESP8266WebServer сервер (80); // Сервер на порту 80
void handleRoot () {
Строка s = MAIN_page; // Чтение содержимого HTML
server.send (200, "text / html", s); // Отправить веб-страницу
}
void handleADC () {
int a = analogRead (A0);
String adcValue = String (a);
server.send (200, «текст / плоскость», adcValue); // Отправляем значение ADC только клиентскому ajax-запросу
}
void handleLED () {
String t_state = server.arg ("LEDstate");
Serial.println (t_state);
server.send (200, «текст / плоскость», t_state); // Отправить веб-страницу
}
void setup (void) {
Serial.begin (115200);
WiFi.begin (ssid, пароль); // Подключаемся к вашему WiFi роутеру
Serial.println ( "");
while (WiFi.status ()! = WL_CONNECTED) {
задержки (500);
Serial.print ( "");
}
Serial.println ( "");
Serial.print («Подключен к»);
Serial.println (SSID);
Serial.print («IP-адрес:»);
Serial.println (WiFi.localIP ()); // IP-адрес, назначенный вашему ESP
server.on ("/", handleRoot); // Какую процедуру обработать в корневом расположении. Это страница отображения
server.on ("/ setLED", handleLED);
server.on ("/ readADC", handleADC);
server.begin (); // Запустить сервер
Serial.println («HTTP-сервер запущен»);
}
void loop (void) {
server.handleClient (); // Обработка клиентских запросов
}
Файл "index.h"
const char MAIN_page [] PROGMEM = R "===== (
<! DOCTYPE html>
<HTML>
<meta charset = "utf-8">
<Тело>
<div id = "demo">
<h1> Аякс ... </ h1>
<button type = "button" onclick = "sendData (1900)"> 190.0 </ button>
<button type = "button" onclick = "sendData (2000)"> 200.0 </ button>
<button type = "button" onclick = "sendData (2100)"> 210.0 </ button>
<button type = "button" onclick = "sendData (2200)"> 220.0 </ button>
<BR>
<BR>
</ DIV>
<DIV>
Значение ADC: <span id = "ADCValue"> 0 </ span> <br>
</ DIV>
<Скрипт>
function sendData (led) {
var xhttp = new XMLHttpRequest ();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
document.getElementById ("LEDState"). innerHTML =
this.responseText;
}
};
xhttp.open ("GET", "setLED? LEDstate =" + led, true);
xhttp.send ();
}
setInterval (function () {
// Повторно вызвать функцию с интервалом 2 секунды
получить данные();
}, 2000); // частота обновления 2000 мсек
function getData () {
var xhttp = new XMLHttpRequest ();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
document.getElementById ("ADCValue"). innerHTML =
this.responseText;
}
};
xhttp.open ("GET", "readADC", true);
xhttp.send ();
}
</ Скрипт>
</ Body>
</ Html>
) ===== ";
Всё хорошо работает, заранее заданные значения кнопок отправляются и обрабатываются без перезагрузки страницы. Но как нужно доработать код, чтобы это была форма ввода текста? Вообще мне нужен ввод произвольных цифр от 0 до 255 и последующая отправка и обработка без перезагрузки страницы. Кто-то сможет код подсказать?
<input type="text" id="ledval"/> <button type="button" onclick="sendData()">send data</button> ... xhttp.open( "GET", "setLED?LEDstate=" + document.getElementById("ledval").value, true);<input type="text" id="ledval"/> <button type="button" onclick="sendData()">send data</button> ... xhttp.open( "GET", "setLED?LEDstate=" + document.getElementById("ledval").value, true);Отлично! Спасибо!!! То, что надо.
А то я лепил такую конструкцию
И при нажатии на кнопку сразу следовало обновление страницы...