0

只是想用ajax而不是一个动作来提交一个表单,但仍然没有运气。php 脚本有效,并且已通过操作提交进行测试。

到目前为止,我查看了示例,阅读了文档,提出了 SO 问题,但我仍然没有答案。我需要帮助,我本打算在两周前测试这个用例。

当我提交页面看起来像刷新但没有任何反应。用户帐户未插入数据库,并且不出现警告框。谁能看到出了什么问题?

javascript看起来像这样:

    $(document).ready(function()
{

$.validator.addMethod("uniqueuser", function(username){
    var response
    $.ajax({
        type: "POST",
        url: "check_username.php",
        data: "username=" + username,
        success: function(server_response){


                if(server_response == '0'){

                    response = true;
                }
                else if(server_response == '1'){

                    response = false;
                }

        }
    });
    return response;
}, "Username is not available");



$("#createaccount).validate({
    debug: false,
    rules:{
        fname:{
            required: true
        }
        surname:{
            required: true
        }
        email:{
            email:true,
            required: true
        }
        location:{
            required:true
        }
        username:{
            minlength: 6,
            required:true,
            uniqueuser:true
        }
        password:{
            required:true,
            minlength: 6
        }
        re_password:{
            required:true,
            equalTo: "#password"
        }
    }


    submitHandler: function(form){
        $.ajax({
            type: 'POST',
            url: 'createaccount2.php',
            data: $("#createaccount").serialize(),
            success: function(response){

                if(response == "1"){
                    alert("That username is already taken!");
                }
                else if(response == "2"){
                    alert("An account is already registered to that email address");
                }
                else if(response == "3"){
                    alert("Your account has been created!");
                }
                else if(response == "4"){
                    alert("Something went wrong, your account could not be created");
                }
            }

        });


    });
});
});

有关验证器的信息:http: //docs.jquery.com/Plugins/Validation

4

3 回答 3

1

脚本中有很多问题。所有这些都与您正在使用的验证器插件明显相关。一种是异步调用。

当你使用时$.validator(我不知道这个插件,你能添加引用吗?)你尝试return response;设置 ASYNC。(在 AJAX 得到服务器响应之后)。这就是 AJAX 有回调函数的原因,因为你不知道什么时候会设置。

发生了什么?returnAJAX 完成之前执行 get 并修改变量(但范围很好)。

修复?您需要深入研究该验证器插件以查看它是否支持异步验证。

否则,您将需要设置自己的脚本验证。

于 2012-08-06T03:22:29.970 回答
0

您如何将表单提交与表单相关联?您需要在 Form onSubmit 事件中做点什么吗?或使用提交事件处理程序?

<form id="target" action="destination.html">

像这样

$('#target').submit(function() {
  alert('Handler for .submit() called.');
  return false;
});

更多信息:http ://api.jquery.com/submit/

于 2012-08-06T03:19:57.380 回答
0
    <form id="target" onSubmit="return false;">
于 2012-08-06T05:19:09.353 回答