【问题标题】:How to send data to the server via Ajax?如何通过 Ajax 向服务器发送数据?
【发布时间】:2017-01-26 11:53:12
【问题描述】:
注册表单必须是 Ajax,才能通过 Ajax 向服务器发送数据。单击提交时会出现一个旋转的齿轮。如果注册成功,则显示“您已成功注册”消息,如果没有出现错误消息“无效的电子邮件地址”或“用户名已存在”等。
- 我们包含 jQuery 库页面
- JQuery 添加不再提交表单的事件
- 在提交执行ajax时添加了一个带有jQuery的事件
- 根据到达 Ajax 的消息,是否显示成功或失败
【问题讨论】:
标签:
javascript
php
jquery
html
ajax
【解决方案1】:
这一切都大大简化了,但在 javascript 方面,您可以这样做:
var params = {"email": $("input#email")
$.post(yourserver.php, params, validate, "json")
function validate(response) {
if (response.success) {
console.log("Allgood")
} else {
console.log(response.message)
}
}
在 php 服务器端,您的 server.php 可能如下所示:
<?
if ( $_REQUEST["email"] ) {
$response = array("success" => true)
} else {
$response = array("success" => false, "message" => "Missing email");
}
echo json_encode($response);
?>
【解决方案2】:
function success(answer) {
$(".loader").hide(); // Hide loader element
// Back-end side must return 3 numbers, where is
// 1 - success
// 2 - invalid email
// 3 - username already exists
if (answer === 1) { // if returned code "1" then output message of success
console.log("You have successfully registered");
} else if (answer === 2) { // if returned code "2" then output message of invalid email
console.log("Invalid Email Address");
} else if (answer === 3) { // if returned code "3" then output message of username already exists
console.log("Username already exists");
}
function loading() {
$(".loader").show(); // Show loader element
}
$("#submit").on("submit", function() {
$.ajax({
url: ("/handler"), // url address of your handler
type: "POST",
data: ({
email: $("input#email"),
login: $("input#login"),
password: $("input#password")})
beforeSend: loading, // should call loading() without arguments
success: success, // should call success(answer) where answer is result which returned your server
});
});