1 回答
TA贡献1839条经验 获得超15个赞
document.ready当它们尚未定义时,您将获得表单值:
$(document).ready(function () {
var matchID = $('#matchID').val();
var homeScore = $('#homeScore').val();
var awayScore = $('#awayScore').val();
您必须在form提交时获取值,以便required尊重字段上的属性。
所以你必须改变你的html:
<form method="POST">
<label>Match ID :</label>
<input id="matchID" name="matchID" required type="number"><br>
<label>Home Score:</label>
<input id="homeScore" name="homeScore" required type="number"><br>
<label>Away Score:</label>
<input id="awayScore" name="awayScore" required type="number"><br>
<button id="addScoreButton">Add score</button>
</form>
<button id="retrieveScoreButton">Retrieve all scores</button>
还有你的 JavaScript(请注意评论):
$(document).ready(function() {
$(document).on('submit', 'form', function() {
// Here you get the values:
var matchID = $('#matchID').val();
var homeScore = $('#homeScore').val();
var awayScore = $('#awayScore').val();
// OR
// you have a simpler option:
// var data = this.serialize();
$.ajax({
type: 'POST',
data: {
MatchID: matchID,
Home_Score: homeScore,
Away_Score: awayScore
},
// OR
// data: data, // if you use the form serialization above
url: "/addScore",
success: added,
error: showError
});
});
$("#retrieveScoreButton").click(function() {
console.log(id);
$.ajax({
type: 'GET',
dataType: "json",
url: "/allScores",
success: showScores,
error: showError
});
});
});
添加回答
举报