我将使用AJAX和PHP文件处理HTML表单来管理数据,但是成功消息或错误消息都不起作用。 我尝试过firebug,但是当它出现在$ .ajax语句中时它会等待它然后它会崩溃"。
<form id="alcoholic-form" name="alcoholic-form" method="post">
<fieldset>
<input type="submit" id="submit" value="Invia">
</fieldset>
</form><!-- form -->
<div id="risultato"></div>
<div id="errore"></div>
controller.js文件:
$(document).ready(function(){
$("#submit").click(function(){
//var formData = $("#alcoholic-form").serialize();
var nome = "nico";
var cognome = "basi";
$.ajax({
type: "POST",
url: "prova.php", //data manager
data: "nome=" + nome + "&cognome=" + cognome, //data to server
dataType: "html", //return value format
success:function(msg){
$("#risultato").html(msg);
alert(msg);
},//success
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
});//ajax
});//submit click
});//document ready
然后是prova.php文件:
<?php /* questionario.php */ ?>
<?php
$nome = $_POST['nome'];
$cognome = $_POST['cognome'];
echo "nome = " . $nome . " cognome = " . $cognome;
?>
提前谢谢
答案 0 :(得分:5)
您有一个带有提交按钮的表单,当您单击提交按钮时,默认操作是提交表单。
由于您使用的是ajax请求,因此需要阻止默认表单提交。你可以调用event.preventDefault()来做到这一点。
$(document).ready(function () {
$("#submit").click(function (e) {
//prevent the default form submit
e.preventDefault();
//var formData = $("#alcoholic-form").serialize();
var nome = "nico";
var cognome = "basi";
$.ajax({
type: "POST",
url: "prova.php", //data manager
data: "nome=" + nome + "&cognome=" + cognome, //data to server
dataType: "html", //return value format
success: function (msg) {
$("#risultato").html(msg);
alert(msg);
}, //success
error: function (xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
}); //ajax
}); //submit click
}); //document ready
但是由于你有一个表单和一个提交按钮,处理按钮的click事件的表单的提交事件会更好
$(document).ready(function () {
$("#alcoholic-form").submit(function (e) {
//prevent the default form submit
e.preventDefault();
//var formData = $("#alcoholic-form").serialize();
var nome = "nico";
var cognome = "basi";
$.ajax({
type: "POST",
url: "prova.php", //data manager
data: "nome=" + nome + "&cognome=" + cognome, //data to server
dataType: "html", //return value format
success: function (msg) {
$("#risultato").html(msg);
alert(msg);
}, //success
error: function (xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
}); //ajax
}); //submit click
}); //document ready
答案 1 :(得分:0)
我认为它带有ajax数据
$.ajax({
type: "POST",
url: "prova.php", //data manager
data: { nome: nome, cognome: cognome}, //data to server
dataType: "html", //return value format
success:function(msg){
$("#risultato").html(msg);
alert(msg);
},//success
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
});//ajax