gpt4 book ai didi

javascript - 使用 AJAX 编辑 JSON 文件

转载 作者:行者123 更新时间:2023-12-03 04:49:14 25 4
gpt4 key购买 nike

我尝试这样做,当我按下打开按钮时,它会调用turnon()函数,该函数打开名为light.json的JSON文件并在那里写入{“light”:“on”},但它没有为我工作,我不知道为什么。有人可以帮助我吗?

    <?php  
$light = $_GET['light'];
$file = fopen("light.json", "w") or die("can't open file");
if($light == "on") {
fwrite($file, '{"light": "on"}');
}
else if ($light == "off") {
fwrite($file, '{"light": "off"}');
}
?>

<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">

<title>LED for ESP8266</title>

<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">

</head>
<body>
<div class="row" style="margin-top: 20px;">
<div class="col-md-8 col-md-offset-2">

<form>
<input type="button" id="StartButton" value="Turn On" onClick="turnOn()">
</form>
<!--<button onclick="turnOn()">Turn On</button>
<button onclick="turnOff()">Turn Off</button>-->

<div class="light-status well" style="margin-top: 5px; text-align:center">

<script type="text/javascript">
function turnOn() {

$.ajax({

type: "POST",
contentType: "application/json; charset=utf-8",
url: "http://192.168.1.108/test/light.json",
data: {"light": "on"},
dataType: "json",
success: function (data) {
alert(data);
},
error: function (result) {
alert("Error");
}
});
}
</script>

</div>
</div>
</div>
</body>
</html>

谢谢!

最佳答案

您使用 POST 方法发送 AJAX 请求,但尝试使用 PHP 的 GET 方法获取它。

只需将 AJAX 方法从 POST 更改为 GET 即可解决问题。

关于javascript - 使用 AJAX 编辑 JSON 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42733975/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com