當我通過http POST請求發送表單值時,我想要做的是返回「addTemplate.php」的echo值。但是,當我發送請求時,絕對沒有任何反應。認爲我的ajax有問題嗎?
我該怎麼辦?
這裏是我的JS
$(document).ready(function() {
$("#sendTemplate").on("submit", function(event) {
var template = $("#template").val();
event.preventDefault();
$.ajax({method: "POST", url: "addTemplate.php", data: template, success: function(result) {
alert(result);
});
});
});
這裏是我的html
<!DOCTYPE html>
<html>
<head>
<title>Admin</title>
<link type="text/css" rel="stylesheet" href="stylesheet.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="adminscript.js"></script>
</head>
<body>
<h1>Admin/Developer page</h1>
<form id="sendTemplate">
<p>Enter a new template for the server: (Enter #word to enter a placeholder for words)</p><input type="text" name="template" id="template">
<input type="submit" name="submit">
</form>
<div id='success'></div>
<br><br><br><br>
<form action="turing.html">
<button type="submit">Home</button>
</form>
</body>
</html>
這裏是我的PHP
$template = $_POST["template"];
if(strlen($template) <= 100 && strpos($template, "#word")) {
file_put_contents("templates.txt", "\r\n" . $template, FILE_APPEND);
header("Location: http://community.dur.ac.uk/h.j.g.baum/admin.html");
echo "True";
}
else {
echo "False";
}
這有什麼錯我的代碼(最有可能在JavaScript),以及如何我可以改善它嗎?
感謝
在您的ajax中發送的數據需要是ob ject或序列化的字符串。我建議使用'$(this).serialize()' – CodeGodie
現在有很多選項OP – devpro