Javascript Ajax无法正确获取数据
hy 我正在尝试使用ajax提交数据,然后获取数据。我试过这个密码Javascript Ajax无法正确获取数据,javascript,jquery,ajax,Javascript,Jquery,Ajax,hy 我正在尝试使用ajax提交数据,然后获取数据。我试过这个密码 <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>index</title> <link rel="stylesheet" href="css/bootstrap.css"/> </head> <body>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>index</title>
<link rel="stylesheet" href="css/bootstrap.css"/>
</head>
<body>
<div>
<form action="voteupdown.php" id="form" method="post">
<input type="text" name="fname" id="fname" class="form-control"/><br/>
<input type="text" name="lname" id="lname" class="form-control"/><br/>
<input type="submit" name="submit" id="submit" value="Submit"/>
</form>
<div id="result">
</div>
</div>
<script src="js/jquery.js"></script>
<script>
$(document).ready(function(){
$('#form').submit(function(){
return false;
});
$("#submit").click(function(){
$.get(("voteupdown.php"), function (data) {
$("#result").html(data);
});
});
});
</script>
<script src="js/bootstrap.js"></script>
</body>
</html>
任何帮助都将不胜感激。您的服务器端脚本希望向其发送数据,您的javascript正在发送GET请求。此外,GET请求实际上并不包含任何数据 假设您想让服务器端继续等待POST,您应该如下更改javascript
$("#submit").click(function(){
var fname = $('#fname').val();
var lname = $('#lname').val();
$.post("voteupdown.php"), {
fname: fname,
lname: lname
},function (data) {
$("#result").html(data);
});
});
您的代码无法工作,因为PHP需要
$\u POST
变量中的数据。您也没有将任何表单数据发布到PHP文件。
请尝试以下操作:
$('body').on('submit', '#form', function(event) {
event.preventDefault();
var formData = $(this).serialize();
$.ajax({
url: 'voteupdown.php',
type: 'post',
data: formData,
success: function(result) {
$('#result').html(result);
},
error: function(jqXHR, textStatus, errorThrown) {
# error handling here
}
});
});
在表单提交呼叫中使用此代码:
$("#submit").click(function(){
$.post(("voteupdown.php"),
{
fname: $("#fname").val(),
lname: $("#lname").val()
},
function (data)
{
$("#result").html(data);
});
});
使用
post/ajax
在服务器上发送数据,而不是get
如果您有ajax,您也可以删除表单actionI,如下所示。这比我的答案更好,我试图让代码尽可能接近OP的原始版本。我肯定会这样做。
$('body').on('submit', '#form', function(event) {
event.preventDefault();
var formData = $(this).serialize();
$.ajax({
url: 'voteupdown.php',
type: 'post',
data: formData,
success: function(result) {
$('#result').html(result);
},
error: function(jqXHR, textStatus, errorThrown) {
# error handling here
}
});
});
$("#submit").click(function(){
$.post(("voteupdown.php"),
{
fname: $("#fname").val(),
lname: $("#lname").val()
},
function (data)
{
$("#result").html(data);
});
});
You are using $.get method for ajax and you are trying to get val by $_POST. because of this you got this error. Try This hopefully it will help you:
$.post( "voteupdown.php", { fname: $("#fname").val(), lname: $("#lname").val() }, function( data ) {
$("#result").html(data);
});
or if you wants to get response in json format than use this
$.post( "voteupdown.php", { fname: $("#fname").val(), lname: $("#lname").val() }, function( data ) {
$("#result").html(data);
}, "json");