jQuery ajax POST登录请求

时间:2017-06-23 18:38:10

标签: javascript jquery ajax post

我正在尝试通过表单写一个.ajax请求来登录。当我提交表单时,successerror函数都没有任何反应。我注意到如果我在.ajax调用后放置一个警告框,它也不起作用。我希望,如果我只是错误地输入数据,我至少会期望出现错误警告框?这是我的代码:

var clientType = "clienttype"; 
$(document).ready(function(){
    $("#login-form").submit(function(e){
        $.ajax({
            type: "POST",
            url: "myurl",
            data: $(this).serialize() + "&client_type=" + clienttype, 
            success: function(data) {
                alert("sent" + data);  
            }, 
            error: function(){
                alert("Did not work");  
            }
        }); 
        e.preventDefault(); 
    }); 
});

2 个答案:

答案 0 :(得分:1)

我注意到你已经在使用JQuery了。所以也许使用内置的post函数。示例如下:

另请注意:您的变量中有一个轻微的类型:data: $(this).serialize() + "&client_type=" + clienttype,客户类型声明为大写T:clientType

var clientType = "clienttype"; 
$(document).ready(function(){
    $("#login-form").submit(function(e){
        e.preventDefault();
        $.post("myurl",{data:$(this).serialize(),client_type:clientType},function(data){
            console.log("Date returned from request:",data);
            // Returns JSON Data. So data.clientType.
        },'json');

    });
});

答案 1 :(得分:0)

如果你添加一个触发器来取消提交的页面,它应该可以工作(返回false;),看看下面。

var clientType = "clienttype"; 
$(document).ready(function(){
    $("#login-form").submit(function(){
        $.ajax({
            type: "POST",
            url: "myurl",
            data: $(this).serialize() + "&client_type=" + clienttype, 
            success: function(data) {
                alert("sent" + data);  
            }, 
            error: function(){
                alert("Did not work");  
            }
        });

        return false;
    }); 
});