[英]How to submit a form and get some text in return using Ajax
这是我的小提琴代码:
$("form.signupform").submit(function(e) { e.preventDefault(); var data = $(this).serialize(); var url = $(this).attr("action"); var form = $(this); // Add this line $.post(url, data, function(data) { $(form).children(".signupresult").html(data.signupresult); $(form).children(".signupresult").css("opacity", "1"); }); return false; });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <form class="signupform" method="post" action="admin/signupinsert.php"> <p class="signupresult"></p> <input type="text" name="firstname" /> <input type="submit" value="Sign Up"/> </form>
Signupinsert.php页面代码:
// Code to insert data into Database
$signupresult = "Some value here";
$response = new \stdClass();
$response->signupresult = $signupresult;
header('Content-Type: application/json');
print json_encode($response);
预期结果:
当用户单击“提交表单”按钮时,代码在后台运行。 并提交表单,而无需重新加载页面。
然后signupinsert.php
页面返回一些文本,并且其文本显示在带有class signupresult
的段落中。
表单可以无限次提交,而无需重新加载页面。
问题:
该表格只提交一次。 如果我尝试提交两次,则“什么都不会发生”(没有任何值插入数据库,没有在段落中返回带有class signupresult
。
问题出在哪儿?
您必须告诉您的请求,您希望JSON作为返回值。 否则data.signupresult没有意义; 数据被视为字符串。
我总是使用$ .ajax,从不使用$ .post; 我发现添加选项更加容易。
$.ajax({
url: $(this).attr("action"),
dataType: 'JSON',
type: 'post',
data: $(this).serialize(),
success: function(data) {
...
}
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.