我和爸爸正在开发一个项目,我们希望创建一个脚本,在将数字提交到表单中时调用数据。例如,当您输入 ID 号码然后按 ENTER 或 SUBMIT 时,表格将打印/显示信息。这是一个学校项目,因此,例如,当学生提交 ID 号时,它会读取他们的第一节课。
我有以下脚本代码来设置表单:
<form id="firstPeriod" action="firstPeriod.html">
<p>Find your first period.</p>
<p><label>Student no.: <input type="text" name="studentNo"></label></p>
<p><input type="submit" value="Find it"></p>
<p id="result"></p>
</form>
<script type="text/javascript">
$(function() {
$('#firstPeriod').submit(function() {
$.ajax({ // Send the request behind the scenes
url: $(this).attr('action'), // Send it here
data: $(this).serialize(), // With this student no.
success: function(data) {
$('#result').html(data); // Display the resulting HTML
},
error: function(jqxhr, status, error) {
console.log(error);
$('#result').html('No results found. Please check your number and reenter'); // Notify an error
}
});
return false; // Prevent the normal form submission
});
});
我的问题是,组织数据的最佳方式是什么?数组、HTML 等? ID号码相当多,目前是在HTML表格中设置的,但在调用信息时似乎不起作用。我希望数据是具体的。因此,当输入特定的 ID 号码时,它会读取特定的答案。现在我的问题是,当我输入一个数字时,它会读取几个类。
如果有任何建议/意见/其他帖子可以帮助我,我将不胜感激。我有扎实的 HTML、CSS 经验,但我仍在学习 JS 和 jQuery,所以这对我来说有点新鲜。谢谢!
最佳答案
编辑、更新
注意,向 input type="text"
元素添加了 value
属性
<input type="text" name="studentNo" value="" />
在 input type="submit"
元素处用 .on("click")
替换 .submit()
两种可能的方法是 1) 使用 HTML
存储数据,使用 .load()
检索 html
文件中的片段标识符;或 2) 使用 JSON
存储数据,使用 php
html 位于 firstPeriod.html
<div id="0">data 0</div><div id="1">data 1</div>
JavaScript
$(function() {
var form = $("#firstPeriod");
$("input[type=submit]").on("click", function(event) {
event.preventDefault();
event.stopPropagation();
var data = form.serializeArray();
// where `data[0].value` is `id`; e.g.; `0`
var id = data[0].value;
$("#result").load(form.attr("action") +" #"+ id)
})
})
plnkr http://plnkr.co/edit/4onHf9jlJTyDei1zo9IC?p=preview
<小时/>JSON
0.json
{
"0":"<div id='0'>data 0</div>"
}
1.json
{
"1":"<div id='1'>data 1</div>"
}
JavaScript
$(function() {
var form = $("#firstPeriod");
$("input[type=submit]").on("click", function(event) {
event.preventDefault();
event.stopPropagation();
var data = form.serializeArray();
// where `data[0].value` is `id`; e.g.; `0`
var id = data[0].value;
$.post("data.php", {id:id}, function(result) {
$("#result").html(result[id])
}, "json")
})
})
php
<?php
if (isset($_POST["id"])) {
$id = $_POST["id"];
$file = $id . ".json";
if (file_exists($file)) {
$jsondata = file_get_contents($file);
$id_data = json_decode($jsondata, true);
echo json_encode($id_data);
};
}
关于javascript - jQuery/ajax 数据容器+组织,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37076642/