如何通过Ajax将数据发送到服务器?

时间:2016-09-18 20:10:08

标签: javascript php jquery html ajax

注册表必须是Ajax,才能通过Ajax将数据发送到服务器。当您单击提交时出现旋转齿轮。如果注册成功,则显示消息“您已成功注册”如果没有出现错误消息“无效的电子邮件地址”或“用户名已存在”等,

  • 我们包含jQuery库页面
  • JQuery添加一个不再提交表单的事件
  • 在提交执行ajax
  • 时,使用jQuery添加了一个事件
  • 根据发给Ajax的消息,是否显示成功或失败

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:-1)

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
 });
});