2016-06-13 67 views
0

我有一个HTML页面,它提供了电子邮件ID和密码的输入字段,我使用这些值通过节点js express应用程序与我的后端SQL服务器连接。重定向一个页面,并通过javascript显示一条消息

我有一个app.post()方法与SQL连接。

app.post('/user', function (req, res, body) { 
uid = req.body.user1; 
pwd = req.body.user2; 

    config = 'Server={ip of server};Database=Dbname;Uid=domain\\user' + uid + ';Pwd=' + pwd; 

    var dbConn = new sql.Connection(config); 
    dbConn.connect().then(function() {           //using promises instead of callbacks(onceconnect() is done), then go to then() 

     var request = new sql.Request(dbConn); 
     console.log('DONE'); 
    res.status(500).json({ status: 'done' }) 

    }).catch(function (err) { 

     console.log("INVALID"); 
    res.status(500).json({ status: 'invalid' }) 
}); 

我想实现的是 -

  1. 如果凭证是有效的,显示“完成”,在客户端的警报。
  2. 如果凭据无效,则在客户端显示警告“INVALID”。

当前,如果一切都有效,则在/ user处有DONE。 如果ID和密码不匹配,则在/ user处有INVALID。

我的客户端代码

<!DOCTYPE html> 
<html> 

<body> 

<form id ="target" action="/user" method="post"> 
    UserID : <input id="uid" type="text" name="user1" />      <!text fields for date input> 
    Password : <input id="pwd" type="password" name="user2" /> 

    <input id="Submit1" type="submit" value="LOGIN"/>  <!--<!submit button>--> 
    <input id="Button" type="button" value="show graphs" onclick="btntest_onclick()" /> 
</form> 

$.post("/user", function (data) { 
    $("#target").html(data) 
    alert("Data Loaded: " + data); 
}); 

<script type="text/javascript"> 
    function btntest_onclick() { 

    setTimeout(function() { 

     window.location.href = "/../"; 
    },500); 
} 
</script> 
</body> 
</html> 

我无法使用在客户端$。员额()来检索数据回从用户给出了500错误。 我该如何继续?请帮帮我。

+0

首先你使用setTimeOout,它有两个参数,第一个回调第二次参数我没有看到任何时间参数。 当你收到任何错误时,你尝试发送回应的第二件事。但是,如果用户名和密码无效,肯定会从数据库中得到一个错误或其他响应 –

+0

好的,我必须添加一些时间参数。但即使没有,我从数据库中得到的错误显示在控制台上时,我写console.log(),但我希望它在一个警报 –

+0

,所以你发送该错误作为响应,并尝试在客户端处理。警报是webapi将无法在nodejs中工作 –

回答

0

我可以通过使用返回数据到客户端的jquery ajax回调来解决此问题。

$("#target").submit(function (event) { 

    var formData = { 
     'uid': $('input[name=uid]').val(), 
     'pwd': $('input[name=pwd]').val() 
    }; 

    $.ajax({ 
     type: 'POST', // define the type of HTTP verb we want to use (POST for our form) 
     url: '/user', // the url where we want to POST 
     data: formData, // our data object 
     dataType: 'json', // what type of data do we expect back from the server 
     encode: true 
    }) 
    .error(function (data) { 

     // log data to the console so we can see 
     alert(data.responseText); 
    }) 
    .done(function (data) { 

     // log data to the console so we can see 
     console.log(data); 

     // here we will handle errors and validation messages 
    }); 
    event.preventDefault(); 

}); 
+0

是啊......我告诉你......早些时候检查done函数中的数据,并根据响应来决定是否停留在同一页面上并显示警报或重定向页面 –

+0

yes做到了,谢谢 –

相关问题