Ajax-为什么我得到错误函数而不是成功? [英] Ajax- Why do I get an error function instead of success?

查看:99
本文介绍了Ajax-为什么我得到错误函数而不是成功?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白为什么我的代码运行错误功能而不是成功.我一直从console.log

I don't understand why is my code running the error function instead of success. I keep getting this from my console.log

Object {readyState: 0, getResponseHeader: function, getAllResponseHeaders: function, setRequestHeader: function, overrideMimeType: function…}

我想不出为什么它不执行我的逻辑,所以我尝试将重定向放在我的错误函数中,这就是我得到的

I could not think of any reason why won't it execute my logic so I tried putting a redirect in my error function and this is what I get

Object {readyState: 0, getResponseHeader: function, getAllResponseHeaders: function, setRequestHeader: function, overrideMimeType: function…}
基本上发生了同样的事情,所以到目前为止,在编辑windows to window之后,我对问题出在什么地方一无所知. 这是我在js中的代码

Object {readyState: 0, getResponseHeader: function, getAllResponseHeaders: function, setRequestHeader: function, overrideMimeType: function…}
Basically the same thing happened so as of now I don't really have an idea as to what my problem is after editing the windows to window. This is my code in js

function login(){
var username = document.getElementById("userID").value;
var password = document.getElementById("Password").value;
var postData = { "userID": username, "Password": password };
var postJSON = JSON.stringify(postData);

$.ajax({
    url: "http://localhost:3000/api/login", // server url
    type: "POST", //POST or GET
    contentType: "application/json",
    data: postJSON, // data to send in ajax format or querystring format
    datatype: "JSON",

    success: function(response) {
        alert('success');
        console.log(response);
        window.location.replace("http://localhost/index.html");
    },
    error: function(response) {
        alert('error');
        console.log(response);
        window.location.replace("http://localhost/index.html");

    }
});
}

这是我的html代码.我正在使用onclick.

This is my html code. I am using onclick.

 <input class="button" type="submit" id="submit" value="Log In" onclick="return login()"/>

那么我的代码到底出了什么问题?我试图通过ajax用post调用我的登录api(localhost:3000/api/login),然后将检查mongodb的正确条目并输出Login Success,然后如果输入正确,则重定向到另一页,如果输入正确,则停留在同一页上通过提供输出无效的登录ID或密码",输入是错误的.

So exactly what went wrong in my code? I am trying to call my login api (localhost:3000/api/login) through ajax with post which would then check mongodb for correct entries and output Login Success which then redirect to another page if input is correct and stay on the same page if input is wrong by giving output "Invalid Login ID or Password".

更新:

服务器端代码

var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017/myproject';

var authenticate = function(db, req, callback){
var cursor = db.collection('LoginID').find({"_id" : req.body.userID, 
"Password" : req.body.Password
}).count(function(err,doc){
        if(err) return callback(err);
        if(doc == 0){
            console.log('Invalid Login ID or Password');
            return callback(null, doc);
        } else {
            console.log('Login Success');
            return callback(null, doc);
        }
    });
}
module.exports = {
postCollection : function(req,res){
    var username = req.body.userID;
    var Password = req.body.Password;
    //var createdDate =  "<b>" + day + "/" + month + "/" + year + "</b>"
    MongoClient.connect(url, function(err, db) {
        //assert.equal(null, err);
        if(err) {
            res.send(err);
            res.end();
        }
        authenticate(db, req, function(err,doc) {
            if(err)
                res.send(err);
            else{
                    if(!doc){
                        res.send( ' Invalid Login ID or Password ' );
                        res.end();
                    } else {
                        res.send("Login success")
                        res.end();
                    }
                }
            db.close();
        });
    });
}   
}   

推荐答案

如果我没记错的话,只有在HTTP返回码为2xx时才调用成功回调. 如果发送回重定向,则将其视为错误.

If I remember correctly, the success callback is only called if the HTTP return code is 2xx. If you send back a redirection, it is considered as an error.

文档中提到了它:

如果请求成功,则状态为 代码函数采用与成功回调相同的参数; 如果 会导致错误(包括3xx重定向),它们采用相同的 参数作为错误回调.

If the request is successful, the status code functions take the same parameters as the success callback; if it results in an error (including 3xx redirect), they take the same parameters as the error callback.

来自 http://api.jquery.com/jquery.ajax/, statusCode部分.

From http://api.jquery.com/jquery.ajax/, statusCode section.

此外,您必须要小心:如果AJAX请求收到302响应,它将不会进行重定向:这是您的网络浏览器(经典导航)的用户代理,它会自动执行此操作,但对于XHR/AJAX,您必须实现它.

Moreover, you have to be careful: if an AJAX request receives a 302 response, it won't do a redirection: that is the user agent of your web browser (classic navigation) that does that automatically, but for XHR/AJAX, you have to implement it.

这篇关于Ajax-为什么我得到错误函数而不是成功?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆