。我想在文本框中键入值时将数据插入数据库....我的ajax编码没有工作....即使我没有得到任何错误......
尽快帮帮我
我的ajax编码是:
var userid = '#uid';
var datas = 'uid=' + $(userid).val();
$(document).ready(function() {
$("#uid").on("keyup", function() {
$ajax({
type: "GET",
contentType: "text/plain; charset=utf-8",
url: "insert.jsp", //insert.jsp
dataType: 'text',
data: datas, //data to be sent as a parameter cname=babu&mobileno=9877&boxno=
success: function(result) {
alert(result);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Error: " + textStatus + " HttpStatus: " + XMLHttpRequest.status + " " + errorThrown + "\n");
}
});
});
});
我用于插入记录的jsp代码是:
<%
String uid=request.getParameter("uid");
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","testing");
Statement st=con.createStatement();
int i=st.executeUpdate("insert into insert1(usrid) values('"+uid+"')");
if(i>0){
%>Inserted Successfully.... If you want to insert another value means then click here<a href="index.jsp">Insert</a>
<p>Other Wise<a href="listuser.jsp">List User</a>
<%}else{%>
The information you are entered is wrong<a href="index.jsp">Retry</a>
<%}%>
答案 0 :(得分:2)
将语句移到keyup
事件处理程序中。这将获得textbox
中的输入值,并将ajax
发送给服务器。
$("#uid").on("keyup", function() {
var datas = 'uid=' + $(userid).val(); // Move inside event handler
您还可以使用$(this)
获取值:
var datas = 'uid=' + $(this).val();
答案 1 :(得分:1)
使用数据对象发送参数而不是字符串,这是一种干净的方法,并且具有更好的可读性。并获取keyup
函数内的输入值。
试试这个
$(document).ready(function(){
$("#uid").on("keyup",function(){
var val = this.value; //get the input value here.
$.ajax({
type: "GET",
url: "insert.jsp",//insert.jsp
data:{uid : val}, //use data object to send as parameters rather than string.
success: function (result) {
alert(result);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Error: "+textStatus +" HttpStatus: "+XMLHttpRequest.status+" "+errorThrown+"\n");
}
});
});
});