如何通过Ajax向服务器发送数据

How to send data to the server via Ajax?

本文关键字:数据 服务器 何通过 Ajax      更新时间:2023-09-26

注册表单必须是Ajax的,以便通过Ajax向服务器发送数据。当你点击提交出现一个旋转的齿轮。如果注册成功,则消息"您已成功注册",如果没有出现错误消息"无效的电子邮件地址"或"用户名已经存在"等。

    我们包含jQuery库页面
  • JQuery添加不再提交表单的事件
  • 添加了一个jQuery事件,当提交执行ajax
  • 根据到达Ajax的消息显示成功或失败

这一切都大大简化了,但在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);
?>
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
 });
});