ajax表单后的重定向从客户端提交

时间:2016-04-29 07:10:19

标签: javascript jquery ajax node.js

您好我是nodejs和ajax的新手我试图将表单提交到数据库然后设置一些会话变量然后重定向到另一个页面我的客户端ajax代码是

<script type='text/javascript'>
                        /* attach a submit handler to the form */
                        $("#comp").submit(function(event) {

                          /* stop form from submitting normally */
                          event.preventDefault();

                          /* get some values from elements on the page: */
                          var $form = $( this ),
                          url = $form.attr( 'action' );

                          /* Send the data using post */
                          var posting = $.post( url, { N1: $('#N1').val(), N2: $('#N2').val(), N3: $('#N3').val(), N4: $('#N4').val()
                          , N5: $('#N5').val(), N6: $('#N6').val(), N7: $('#N7').val(), N8: $('#N8').val(), N9: $('#N9').val() } );

                          /* Alerts the results */
                          posting.done(function( data ) {
                            alert('success');
                            window.location.assign("localhost:3000/User_Creation");
                          });


                        });
                    </script>

和我的服务器端代码如下我不知道这是否是正确的方式去做,所以纠正我,如果我这样做错误的方式我把我的整个服务器文件我不知道在哪里我我错了

var express = require('express');
var mongo = require('mongodb').MongoClient;
var app = express();
var path = require('path');
var bodyParser = require("body-parser");
var url = 'mongodb://localhost:27017/test';
var assert = require('assert');
var MongoClient = require('mongodb').MongoClient;
var session = require("express-session");
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);



users = [];
connections = []
app.set('view engine', 'ejs');
app.use(express.static(path.join(__dirname, 'views')));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(session({resave: true, saveUninitialized: true, secret:'iasugdhasjb981234781924789', cookie: { maxAge: 60000 }}));
app.use(bodyParser.json());

app.get('/index', function (req, res) {
    if(!req.session.userId)
    {
        res.render('index.ejs');
    }
    else
    {
        res.redirect('/welcome');
    }
});



app.post('/index', function (req, res) {
        var N1 = req.body.firstname;
        var N2 = req.body.lastname;
        MongoClient.connect(url, function(err, db) {
        if (err) {
            throw err;
        }
        db.collection('OB').find({user_name:N1},{password:N2}).toArray(function(err, result) {
            if (err) {
            throw err;
        }});
    });
});
var resultArray = [];
app.post('/login', function(req, res, next) {
    var N1 = req.body.N1;
    var N2 = req.body.N2;
    MongoClient.connect(url, function(err, db) {
        if (err) {
        throw err;
        }
        db.collection('OB').find({user_name:N1,password:N2}).toArray(function(err, result) {
            if (err) {
                throw err;
            }
            resultArray=result;
            try{
                req.session.userId = result[0]._id;
                req.session.userType = result[0].type;
                if(result[0].type=="root")
                {
                    res.redirect('/New_Company');
                }
                else
                {
                    res.redirect('/welcome');
                }
            }
            catch(e){
                res.redirect('/404_Error');
            }

        });
    });
});

app.get('/404_Error',function(req, res){
    res.render('404_Error.ejs');
});

app.get('/New_Company',function(req, res){
    if(!req.session.userType){
        res.redirect('/404_Error');
    }
    else{
        res.render('create_company.ejs');
    }

});

app.post('/New_Company',function(req, res){
    if(!req.session.userType){
        res.redirect('/404_Error');
    }
    if(req.session.userType!="root"){
        res.redirect('/404_Error');
    }
    var item = {
        company_name: req.body.N1,
        Comp_currency: req.body.N2,
        start_time: req.body.N3,
        end_time: req.body.N4,
        comp_country: req.body.N5,
        phone_no: req.body.N6,
        total_locations: req.body.N7,
        time_zone: req.body.N8
    };/*
    MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
                  if (err) {
                    throw err;
                  }
                  db.collection('company').find({company_name:req.body.N1}).toArray(function(err, result) {
                    if (err) {
                      throw err;
                    }
                    res.redirect('/404_Error');
                 });
            });
    mongo.connect(url, function(err, db) {
        assert.equal(null, err);
        db.collection('company').insertOne(item, function(err, result) {
            assert.equal(null, err);
            console.log('Item inserted');
            db.close();
            MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
                  if (err) {
                    throw err;
                  }
                  db.collection('company').find({company_name:req.body.N1}).toArray(function(err, result) {
                    if (err) {
                      throw err;
                    }
                    console.log(result);
                    req.session.comp_id = result[0]._id;
                    res.redirect('/User_Creation');     
                 });
            });
        });
    });*/
    console.log('Successfully Executed');
});

app.get('/User_Creation', function(req, res){
    res.render('create_user.ejs');
});

app.get('/logout',function(req,res){
    req.session.destroy();
    res.redirect('/index');
});

app.get('/welcome',function(req, res){
    if(!req.session.userId)
    {
        res.redirect('/404_Error');
    }
    else
    {
        res.render('login.ejs',{resultArray:resultArray,id:req.session.userId});
    }
});

app.get('/', function(req, res){
  res.send('DEFAULT PAGE');
});

app.get('/location', function(req, res){
  res.render('location_details.ejs');
});

io.sockets.on('connection',function(socket){
    connections.push(socket);
    console.log('Connected :%s sockets connected',connections.length);

    socket.on('disconnect',function(data){
        connections.splice(connections.indexOf(socket),1);
        console.log('Disconnected: %s sockets connected',connections.length);
    });

    socket.on('send message',function(data){
        console.log(data);
        io.sockets.emit('new message',{msg:data});      
    });
});
server.listen(3000);
console.log("running");

感谢....

1 个答案:

答案 0 :(得分:0)

在网址开头添加http

window.location.assign("http://localhost:3000/User_Creation");