我是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");
});
问题是,当我取消注释//警报("Wfah")时,我在ajax成功中得到结果,然后重定向到add.php。当我不取消注释时,我会直接重定向到addphp。似乎没有调用success。请帮助我。也建议任何好的来源来学习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',
dataType: 'json',
type:'post',
data:contents,
success:function(data)
{
if(data.success)
{
alert("result is " + data.result);
}
}
}
);
// alert("Wfah");
});
您还在PHP代码段中将$json['success']
设置为字符串"true"
。这可能只是一个小的逻辑错误,但可以考虑将其更改为布尔true
文字:
$json['success'] = "true";
进入
$json['success'] = true;