Javascript 在Ajax中使用jquery时,如何不从浏览器更新值?
我的代码有问题。我希望Ajax调用中的URL值不更新两次,而只更新一次。但是代码所做的是,它不断地从URL更新该字段,并且在Ajax调用中,URL的0和1值之间不匹配。请查看此代码中的逻辑,并帮助我改进逻辑。我只希望我的field8=1在BtnOn()函数上只更新一次,因此,如果我单击两次而不刷新页面,那么BtnOff()函数也同样适用。将原始值保持为field8=0的状态。所以它不会在field8=1和它之间做不匹配的事情,这是在做当前不利于用户看到它的事情,同时也不利于状态消息Javascript 在Ajax中使用jquery时,如何不从浏览器更新值?,javascript,jquery,ajax,Javascript,Jquery,Ajax,我的代码有问题。我希望Ajax调用中的URL值不更新两次,而只更新一次。但是代码所做的是,它不断地从URL更新该字段,并且在Ajax调用中,URL的0和1值之间不匹配。请查看此代码中的逻辑,并帮助我改进逻辑。我只希望我的field8=1在BtnOn()函数上只更新一次,因此,如果我单击两次而不刷新页面,那么BtnOff()函数也同样适用。将原始值保持为field8=0的状态。所以它不会在field8=1和它之间做不匹配的事情,这是在做当前不利于用户看到它的事情,同时也不利于状态消息
<div class ="success"></div>
<div class = "warning"></div>
<div class="col-md-2 text-center">
<button id="singlebutton" name="singlebutton" class="btn btn-danger"
onclick="BtnOff();">Off</button> <br>
</div>
<!------
---->
<br/>
<div class = "col-md-2 text-center">
<button id = "singlebtn" name="singlebtn" class="btn btn-success"
onclick = "BtnOn();">On</button> <br>
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
var data;
function BtnOff() {
$.ajax({
url:'https://api.thingspeak.com/update api_key=D***&field8=0',
type:'GET',
data:{
type:'text'
},
success:function(response){
alert(response);
$('div.warning').html('status changed to zero').delay(1000).fadeOut();
$('#singlebutton').append(data);
return false;
}
});
//setTimeout("Subscribe()", 100);
}
// second button to unsubscribe.
function BtnOn() {
$.ajax({
url:'https://api.thingspeak.com/updateapi_key=D***&field8=1',
type:'GET',
data:{
type:'text'
},
success:function(response){
alert(response);
$('div.success').html('status changed to one').delay(1000).fadeOut();
$('#singlebtn').append(data);
return data;
}
});
var h = setTimeout("Subscribe()", 100);
clearTimeout(h);
}
</script>
<!-- Back End--->
/*
Azure IoT Hub WiFi
This sketch securely connects to an Azure IoT Hub using MQTT over WiFi.
It uses a private key stored in the ATECC508A and a self signed public
certificate for SSL/TLS authetication.
It publishes a message every 5 seconds to "devices/{deviceId}/messages/events/" topic
and subscribes to messages on the "devices/{deviceId}/messages/devicebound/#"
topic.
The circuit:
- Arduino MKR WiFi 1010 or MKR1000
This example code is in the public domain.
*/
#include <Wire.h>
#include <Arduino_MKRENV.h>
#include <SPI.h>
#include <ArduinoBearSSL.h>
#include <ArduinoECCX08.h>
#include <utility/ECCX08SelfSignedCert.h>
#include <ArduinoMqttClient.h>
#include <WiFiNINA.h> // change to #include <WiFi101.h> for MKR1000
#include "arduino_secrets.h"
/////// Enter your sensitive data in arduino_secrets.h
const char ssid[] = SECRET_SSID;
const char pass[] = SECRET_PASS;
const char broker[] = SECRET_BROKER;
String deviceId = SECRET_DEVICE_ID;
String mqttPassword = SECRET_MQTT_PASSWORD;
WiFiClient wifiClient; // Used for the TCP socket connection
BearSSLClient sslClient(wifiClient); // Used for SSL/TLS connection, integrates with ECC508
MqttClient mqttClient(sslClient);
unsigned long lastMillis = 0;
unsigned long postNumbers = 0;
float temperature, humidity, pressure, illuminance, uva, uvb, uvIndex;
String jsonString = "";
void setup()
{
Serial.begin(9600);
while (!Serial);
if (!ENV.begin())
{
Serial.println("Failed to initialize MKR ENV shield!");
while (1);
}
if (!ECCX08.begin())
{
Serial.println("No ECCX08 present!");
while (1);
}
// reconstruct the self signed cert
ECCX08SelfSignedCert.beginReconstruction(0, 8);
ECCX08SelfSignedCert.setCommonName(ECCX08.serialNumber());
ECCX08SelfSignedCert.endReconstruction();
// Set a callback to get the current time
// used to validate the servers certificate
ArduinoBearSSL.onGetTime(getTime);
// Set the ECCX08 slot to use for the private key
// and the accompanying public certificate for it
sslClient.setEccSlot(0, ECCX08SelfSignedCert.bytes(), ECCX08SelfSignedCert.length());
// Set the client id used for MQTT as the device id
mqttClient.setId(deviceId);
// Set the username to "<broker>/<device id>/api-version=2018-06-30" and empty password
String username;
username += broker;
username += "/";
username += deviceId;
username += "/api-version=2018-06-30";
mqttClient.setUsernamePassword("MKR1010", mqttPassword);
// Set the message callback, this function is
// called when the MQTTClient receives a message
mqttClient.onMessage(onMessageReceived);
}
void loop()
{
if (WiFi.status() != WL_CONNECTED)
{
connectWiFi();
}
if (!mqttClient.connected())
{
// MQTT client is disconnected, connect
connectMQTT();
}
// poll for new MQTT messages and send keep alives
mqttClient.poll();
// publish a message roughly every 60 seconds.
if (millis() - lastMillis > 60000)
{
lastMillis = millis();
publishMessage();
readEnvSensors();
}
}
void readEnvSensors()
{
// read all the sensor values
temperature = ENV.readTemperature();
humidity = ENV.readHumidity();
pressure = ENV.readPressure();
illuminance = ENV.readIlluminance();
uva = ENV.readUVA();
uvb = ENV.readUVB();
uvIndex = ENV.readUVIndex();
postNumbers++;
Serial.print("Post number: ");
Serial.println(postNumbers);
// print each of the sensor values
Serial.print("Temperature = ");
Serial.print(temperature);
Serial.println(" °C");
Serial.print("Humidity = ");
Serial.print(humidity);
Serial.println(" %");
Serial.print("Pressure = ");
Serial.print(pressure);
Serial.println(" kPa");
Serial.print("Illuminance = ");
Serial.print(illuminance);
Serial.println(" lx");
Serial.print("UVA = ");
Serial.println(uva);
Serial.print("UVB = ");
Serial.println(uvb);
Serial.print("UV Index = ");
Serial.println(uvIndex);
}
unsigned long getTime()
{
// get the current time from the WiFi module
return WiFi.getTime();
}
void connectWiFi()
{
Serial.print("Attempting to connect to SSID: ");
Serial.print(ssid);
Serial.print(" ");
while (WiFi.begin(ssid, pass) != WL_CONNECTED)
{
// failed, retry
Serial.print(".");
delay(5000);
}
Serial.println();
Serial.println("You're connected to the network");
Serial.println();
}
void connectMQTT()
{
Serial.print("Attempting to MQTT broker: ");
Serial.print(broker);
Serial.println(" ");
while (!mqttClient.connect(broker, 8883))
{
// failed, retry
Serial.print(".");
Serial.println(mqttClient.connectError());
delay(5000);
}
Serial.println();
Serial.println("You're connected to the MQTT broker");
Serial.println();
// subscribe to a topic
mqttClient.subscribe("channels/899906/subscribe/fields/field8/F35GLOFJ8L99D0OM");
}
void publishMessage()
{
Serial.println("Publishing message");
// send message, the Print interface can be used to set the message contents
mqttClient.beginMessage("channels/899906/publish/DLQ0F7W5FGVO1I9Q");
String dataString = String("field1=") + String(temperature) + String("&field2=") + String(illuminance);
mqttClient.print(dataString);
mqttClient.endMessage();
/*
// send message, the Print interface can be used to set the message contents
mqttClient.beginMessage("channels/899906/publish/fields/field1/DLQ0F7W5FGVO1I9Q");
mqttClient.print(temperature);
mqttClient.endMessage();
mqttClient.beginMessage("channels/899906/publish/fields/field2/DLQ0F7W5FGVO1I9Q");
mqttClient.print(illuminance);
mqttClient.endMessage();
*/
}
void onMessageReceived(int messageSize)
{
// we received a message, print out the topic and contents
Serial.print("Received a message with topic '");
Serial.print(mqttClient.messageTopic());
Serial.print("', length ");
Serial.print(messageSize);
Serial.println(" bytes:");
// use the Stream interface to print the contents
while (mqttClient.available())
{
Serial.print((char)mqttClient.read());
}
Serial.println();
Serial.println();
}
关闭
在
var数据;
函数BtnOff(){
$.ajax({
网址:'https://api.thingspeak.com/update api_key=D***&field8=0',
类型:'GET',
数据:{
类型:'text'
},
成功:功能(响应){
警报(响应);
$('div.warning').html('status changed to zero').delay(1000).fadeOut();
$('#singlebutton')。追加(数据);
返回false;
}
});
//setTimeout(“Subscribe()”,100);
}
//第二个按钮取消订阅。
函数BtnOn(){
$.ajax({
网址:'https://api.thingspeak.com/updateapi_key=D***&字段8=1',
类型:'GET',
数据:{
类型:'text'
},
成功:功能(响应){
警报(响应);
$('div.success').html('status changed to one').delay(1000).fadeOut();
$('#singlebtn')。追加(数据);
返回数据;
}
});
var h=setTimeout(“Subscribe()”,100);
清除超时(h);
}
/*
Azure物联网中心WiFi
此草图使用MQTT over WiFi安全地连接到Azure IoT集线器。
它使用存储在ATEC508A中的私钥和自签名公钥
SSL/TLS身份验证证书。
它每5秒钟将一条消息发布到“devices/{deviceId}/messages/events/”主题
并订阅“devices/{deviceId}/messages/devicebound/#”上的消息
话题。
电路:
-Arduino MKR无线1010或MKR1000
此示例代码位于公共域中。
*/
#包括
#包括
#包括
#包括
#包括
#包括
#包括
#包括//更改为#包括MKR1000
#包括“arduino_secrets.h”
///////在arduino_secrets.h中输入您的敏感数据
const char ssid[]=secretu ssid;
const char pass[]=SECRET_pass;
const char broker[]=秘密代理;
字符串设备ID=机密设备ID;
字符串mqttPassword=SECRET_MQTT_PASSWORD;
WiFiClient WiFiClient;//用于TCP套接字连接
BearSSLClient sslClient(wifiClient);//用于SSL/TLS连接,与ECC508集成
MqttClient MqttClient(sslClient);
无符号长lastMillis=0;
无符号长postNumbers=0;
浮子温度、湿度、压力、照度、uva、uvb、uvIndex;
字符串jsonString=“”;
无效设置()
{
Serial.begin(9600);
而(!串行);
如果(!ENV.begin())
{
Serial.println(“初始化MKR环境屏蔽失败!”);
而(1),;
}
如果(!ECCX08.begin())
{
Serial.println(“不存在ECCX08!”);
而(1),;
}
//重构自签名证书
ECCX08SelfSignedCert.beginReconstruction(0,8);
ECCX08SelfSignedCert.setCommonName(ECCX08.serialNumber());
ECCX08SelfSignedCert.endReconstruction();
//设置回调以获取当前时间
//用于验证服务器证书
onGetTime(getTime);
//将ECCX08插槽设置为用于私钥
//以及随附的公共证书
sslClient.setEccSlot(0,ECCX08SelfSignedCert.bytes(),ECCX08SelfSignedCert.length());
//将用于MQTT的客户端id设置为设备id
mqttClient.setId(设备ID);
//将用户名设置为“//api version=2018-06-30”,密码为空
字符串用户名;
用户名+=经纪人;
用户名+=“/”;
用户名+=设备ID;
用户名+=“/api版本=2018-06-30”;
setUsernamePassword(“MKR1010”,mqttPassword);
//设置消息回调,此函数为
//当MQTTClient收到消息时调用
mqttClient.onMessage(onMessageReceived);
}
void循环()
{
如果(WiFi.status()!=WL_已连接)
{
连接WiFi();
}
如果(!mqttClient.connected())
{
//MQTT客户端已断开连接,请连接
connectMQTT();
}
//轮询新MQTT消息并发送保持有效
mqttClient.poll();
//大约每60秒发布一条消息。
如果(毫秒()-lastMillis>60000)
{
lastMillis=millis();
publishMessage();
readEnvSensors();
}
}
void readEnvSensors()
{
//读取所有传感器值
温度=环境读取温度();
湿度=环境读取湿度();
压力=环境读数压力();
照度=环境读数照度();
uva=ENV.readUVA();