我是ajax的新手.作为第一个例子,我想实现一个添加操作.为此,我写了以下代码:
HTML:
<!doctype html> <html> <head> <title>Add two numbers</title> <Meta content="text/html;charset=utf-8" http-equiv="Content-Type"> <Meta content="utf-8" http-equiv="encoding"> <script src="jquery.js"></script> </head> <body> <form id="addForm" method="post"> <input type="text" name="first"> <input type="text" name="second"> <input type="submit" name="btnSubmit"> </form> <script src="global.js"></script> </body> </html>
PHP:
<?PHP header('Content-type: text/html; charset=utf-8'); $json = array('success' => false,'result' => 1 ); if (isset($_POST['first']) && isset($_POST['second'])) { $json['success'] = "true"; $first = $_POST['first']; $second = $_POST['second']; $json['result'] = $first + $second; } echo json_encode($json); ?>
global.js
$('#addForm').on('submit',function () { // alert("hello submit"); var contents = $(this).serialize(); $.ajax( { url:'add.PHP',dataType: 'json',type:'post',data:contents,success:function(data) { if(data.success) { alert("result is " + data.result); } } } ); // alert("Wfah"); });
问题是当我取消注释// alert(“Wfah”);,我得到ajax成功的结果,然后重定向到add.PHP.当我不取消注释时,我被直接重定向到add.PHP.似乎没有成功.
请帮我.也建议任何学习ajax的好资源.谢谢.
解决方法
$('#addForm').on('submit',function (e) { e.preventDefault(); //<----- you need to prevent the form from submitting // alert("hello submit"); var contents = $(this).serialize(); $.ajax( { url:'add.PHP',success:function(data) { if(data.success) { alert("result is " + data.result); } } } ); // alert("Wfah"); });
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。