【发布时间】:2017-08-01 17:14:40
【问题描述】:
我尝试这样做,当我按下打开按钮时,它会调用 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>
谢谢!
【问题讨论】:
-
doesn't work是什么意思?你有错误吗?如果有,有什么错误? -
url: "http://192.168.1.108/test/light.json"- 您不能只将数据“发布”到 JSON 文件的 URL,并期望任何事情都会自动发生。您需要将数据发布到服务器端脚本。在 PHP 文件的开头看到您的代码,这大概是您要发布到的地址。但是你会想要做与肯尼的回答相反的事情,因为如果你使用 GET,你的脚本将在 每个 请求时写入文件,所以当你调用页面时。请改用 POST,并查看 isset/empty 以首先正确检查您的脚本期望的参数是否实际存在。
标签: javascript jquery json ajax post