我正在尝试通过输入输入值使用 jquery 将新数据发布到我的 json 文件中,但是当我这样做时没有任何反应。对于这个有点愚蠢的问题,我提前道歉,非常感谢您的帮助!
我对编程很陌生,但我不知道这是否可行。下面是我的 'index.php' 文件,其中我的 jquery 和按钮用于添加新数据。
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
</head>
<body>
<input type="text" id="name">
<input type="text" id="grade">
<button id="btn">Add</button>
</body>
<script>
$(document).ready(function(){
$.getJSON('http://localhost/mytest/json.php', function(data) {
for (i=0; i < data.length; i++) {
if (data[i].grade < 5) {
document.write("<p style='color: red;'>Name: " + data[i].name + "<br>Grade: " + data[i].grade + "</p>");
} else {
document.write("<p style='color: green;'>Name: " + data[i].name + "<br>Grade: " + data[i].grade + "</p>");
}
}
});
// posting the orders
$('#button').on('click', function() {
var order = {
name: $('#name').val(),
grade: $('#grade').val(),
}
$.ajax({
type: 'POST',
url: 'http://localhost/mytest/json.php',
data: order,
success: function(newStudent) {
}
})
});
});
</script>
</html>
下面是我用 PHP (json.php) 创建的 JSON 文件:
<?php
$student1 = array(
"name"=>"ali",
"grade"=>"7"
);
$student2 = array(
"name"=>"John",
"grade"=>"4"
);
$student3 = array(
"name"=>"Martha",
"grade"=>"2"
);
$student4 = array(
"name"=>"Jullie",
"grade"=>"8"
);
$student5 = array(
"name"=>"Morgan",
"grade"=>"4"
);
$students = array($student1, $student2, $student3, $student4, $student5);
$j = json_encode($students); // we 'encode' the array into a JSON format
echo $j;
?>
PIPIONE