我是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的好资源。谢谢。
答案 0 :(得分:6)
$('#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',
dataType: 'json',
type:'post',
data:contents,
success:function(data)
{
if(data.success)
{
alert("result is " + data.result);
}
}
}
);
// alert("Wfah");
});
答案 1 :(得分:1)
您还要将$json['success']
设置为PHP代码段中的字符串"true"
。这可能只是一个小的逻辑错误,但考虑将其更改为布尔true
文字:
$json['success'] = "true";
向
$json['success'] = true;