我正在尝试创建一个使用jQuery将数据插入数据库的表单,但是没有任何操作发生,并想知道问题所在。
这是我写的代码,我希望有人能帮助我找出错误的位置,以及为什么没有采取任何行动。
的index.html:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="insert.js"></script>
</head>
<body>
<form id="form-search" method="post" action="index.html">
<input name="gov" id="gov" type="text" class="textinput required" maxlength="80" required><br>
<input name="area" id="area" type="text" class="textinput required" maxlength="80" required><br>
<button id="submit" type="button">insert</button>
</form>
</body>
</html>
insert.js code
$(document).ready(function(e) {
$('#submit').click(function() {
var gov =$('#gov').val() ;
var area =$('#area').val() ;
$.ajex({
type :'post' ,
data :{gov:gov,area:area},
url :"insert.php",
success :function(result) {
alert(result);
}
})
});
});
insert.php code
<?php
$con = mysqli_connect('localhost','user','pass','db');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
if($_REQUEST['gov']) {
$gov=$_REQUEST['gov'];
$area=$_REQUEST['area'];
$q="inser into gov values ('','$gov','$area')";
$query=mysqli_query($con,$q);
if($query){
echo "data insert " ;
}
}
?>
答案 0 :(得分:0)
此脚本(使用您的html)将数据(带有控制台日志到浏览器)提交到&#39; insert.php&#39;。请阅读评论以获得解释。如果它仍然无法正常工作,问题可能在于您的PHP代码(我不能使用PHP)。 ajax将数据发送到&#39; insert.php&#39;,应对其进行编码以接受数据变量并将json响应返回给脚本中的ajax函数。
// Remove the 'e' from .ready and place in the 'click' function - this is the 'event'
$(document).ready(function () {
$('#submit').click(function (e) {
// Stops the form from being submitted 'normally' (to index.html)
e.preventDefault();
// Check console in your browser (this can be removed when it works)
console.log('submit clicked');
// Define the data to be submitted with the ajax form
var submitData = { gov: $('#gov').val(), area: $('#area').val() };
$.ajax({
// Make sure your path to insert.php is complete - check console in browser to see if there is an error
url: 'insert.php',
// Make sure 'insert.php' accepts 'post' transactions
type: 'POST',
// This could be changed (when it works) to - data: { gov: $('#gov').val(), area: $('#area').val() },
data: submitData,
// Make sure 'insert.php' returns a json result
dataType: 'json',
success: function (result) {
// This can be removed when it works
console.log('ajax success');
},
beforeSend: function () {
// This can be removed when it works
console.log('ajax beforeSend');
// This can be removed when it works - this lists out the data submitted with the form
$.each(submitData, function (index, value) {
console.log('index: ' + index + ' value: ' + value);
});
},
complete: function () {
// This can be removed when it works
console.log('ajax complete');
},
error: function () {
// This can be removed when it works
console.log('ajax error');
}
});
});
});
答案 1 :(得分:0)
使用开发人员工具查看“网络”标签。按下提交按钮时,检查是否发生了某些事情。检查状态代码。