2016-09-18 125 views
-6

注册表格必须是Ajax,通过Ajax发送数据到服务器。当你点击提交出现一个旋转的齿轮。如果注册成功,那么消息“您已成功注册”如果不出现错误消息“电子邮件地址无效”或“用户名已经存在”等如何通过Ajax将数据发送到服务器?

  • 我们包括jQuery库页
  • 发生JQuery的添加事件不再做提交表单
  • 加入jQuery的事件,使得提交给执行AJAX
  • 根据消息时来到阿贾克斯,是否显示成功或失败
+1

欢迎到SO。 请阅读[我可以问哪些主题](http://stackoverflow.com/help/on-topic) 和[如何提出一个好问题](http://stackoverflow.com/help/how-to - 问) 和[完美的问题](http://codeblog.jonskeet.uk/2010/08/29/writing-the-perfect-question/) 以及如何创建[最小,完整和可验证的例子] (http://stackoverflow.com/help/mcve) SO是**不是一个免费的编码或代码转换或调试或教程或库查找服务** 您还必须表明,你已经努力解决你自己的问题。 – RiggsFolly

回答

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

这不是一个答案。你应该评论和解释你的代码。 – Anselm

+0

已更改。核实 –

相关问题