使用ajax我如何将phonegap与servlet集成,如果有可能就意味着我在URL中提到的内容 我已经尝试过了,但发生了服务器错误
答案 0 :(得分:2)
非常感谢您的回复,我在这里找到了解决方案,我发布了可能对其他人有用的代码
Servlet(服务器端): protected void doPost(HttpServletRequest request,HttpServletResponse response)抛出ServletException,IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
Connection con = null;
ResultSet resultSet = null;
String uname = request.getParameter("uname");
String pwd = request.getParameter("pwd");
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
String url = "jdbc:mysql://localhost/ROSE";
final String USER = "root";
final String PASS = "root";
con = DriverManager.getConnection(url,USER,PASS);
String query = null;
query = "SELECT uname,pwd from roobi";
PreparedStatement statement = con.prepareStatement(query);
resultSet = statement.executeQuery();
String db_uname="";
String db_pwd="";
while (resultSet.next()) {
db_uname = resultSet.getString("uname")
db_pwd = resultSet.getString("pwd");
if( (uname.equals(db_uname)) && (pwd.equals(db_pwd))){
out.write("SUCCESS");
} }
} catch (Exception e) {
e.printStackTrace();
} finally {
out.close();
} } }
Phonegap(client side)
<script type="text/javascript" charset="utf-8" src="cordova-2.5.0.js"></script>
<script>
function verifyLogin(){
var uname=document.getElementById("txt_username").value;
var pwd=document.getElementById("txt_pwd").value;
$.support.cors = true;
$.ajax({
type : 'POST',
url : 'http://10.0.2.2:8080/sam/Jdbc', // Servlet URL
data:{
uname:uname,
pwd:pwd,
},
success : function(data) {
if("SUCCESS"==data){
alert("Login Success!!");
} else {
alert("Invalid Login!!");
}
},
error: function (xhr, ajaxOptions, thrownError)
{
alert("errorstatus: " + xhr.status + " ajaxoptions: " + ajaxOptions + " throwError: " + thrownError);
}
});
}
</script>
</head>
<body>
<div data-role="page" id="page1">
<div data-role="content" id="input_login">
<ul data-role="listview" data-divider-theme="b" data-inset="true">
<li data-role="list-divider" role="heading">User Name</li>
<li data-role="list-divider" >
<input type="text" id="txt_username"/></li>
<li data-role="list-divider" role="heading">
Password
</li>
<li data-role="list-divider" >
<input type="password" id="txt_pwd"/>
</li>
<li data-role="list-divider" >
<input type="button" id="btn_login" value="Login" onclick="verifyLogin()"/>
</li>
</ul>
</div>
</div>
</body>