【发布时间】:2016-01-20 13:49:27
【问题描述】:
我正在尝试使用 jQuery / Ajax 将一些表单数据提交到 PHP Web 服务(php 文件)并简单地回显结果。
这是我的 index.html 文件
<html>
<head>
<title>PHP web service & AJAX</title>
<link rel="stylesheet" type="text/css" href="style.css" />
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
</head>
<body>
<h1>Hello! Is it me you're looking for?</h1>
<form id="submit">
<label>Name</label>
<input id="name" type="text" name="name" />
<label>Email</label>
<input id="email" type="email" name="email" />
<input class="submit" type="submit" value="Submit details" />
</form>
<script type="text/javascript">
$(document).ready(function(){
$(".submit").click(function(e) {
e.preventDefault();
// BUILD DATA STRING
var name = $("#name").val();
var email = $("#email").val();
var dataString = "subName=" + name + "&subEmail=" + email;
$.ajax({
type: 'POST',
url: 'results.php',
data: dataString,
success: function() {
window.location.href = "results.php";
}
});
});
});
</script>
还有 PHP (results.php) 文件
<?php
echo $_POST['subName'] . "<br />" . $_POST['subEmail'];
?>
到目前为止没有运气,有人可以帮助我吗?我也尝试过this tutorial 和this one,但它们没有帮助。
【问题讨论】:
-
去掉
window.location.href = "results.php";,使用AJAX时不需要。它会在成功完成 AJAX 后重定向页面,给人的印象是 AJAX 不起作用并且表单已提交并重定向 -
@Tushar 我可以将成功函数留空,脚本就可以了吗?
-
是的,使用
success: function(response) { console.log(response); }, -
我也会推荐使用
data: $('form').serialize(),
标签: javascript php jquery html ajax