我想將多個行插入到Mysql數據庫中,但它不會插入多行,因爲我在用戶按Enter鍵時使用jquery創建的行。 ..在此我有三個文件(HTML)(jQuery的)(JSP與DB)如何在jQuery中創建的mysql中插入多行
HTML
<form action="newjsp.jsp" method="post">
<table width="500" border="1">
<tr>
<td>No.</td>
<td>Name</td>
<td>Age</td>
<td>Phone</td>
<td>Email</td>
</tr>
<tr>
<td>1</td>
<td><input type="text" class="inputs" name="name_1" id="name_1" /></td>
<td><input type="text" class="inputs" name="age_1" id="age_1" /></td>
<td><input type="text" class="inputs" name="phone_1" id="phone_1" /></td>
<td><input type="text" class="inputs lst" name="email_1" id="email_1"/></td>
</tr>
</table>
<input type="submit" value="submit"/>
</form>
</body>
</html>
JQuery的
<script>
var i = $('table tr').length;
這是創建的行數,當用戶按下回車鍵的jQuery
$(document).on('keyup', '.lst', function(e)
{
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 13) {
html = '<tr>';
html += '<form action="newjsp.jsp" method="post">';
html += '<td>' + i + '</td>';
html += '<td><input type="text" class="inputs" name="name_' + i + '" id="name_' + i + '" /></td>';
html += '<td><input type="text" class="inputs" name="age_' + i + '" id="age_' + i + '" /></td>';
html += '<td><input type="text" class="inputs" name="phone_' + i + '" id="phone_' + i + '" /></td>';
html += '<td><input type="text" class="inputs lst" name="email_' + i + '" id="email_ ' + i + '"/></td>';
html += '</form>';
html += '</tr>';
$('table').append(html);
$(this).focus().select();
i++;
}
});
$(document).on('keydown', '.inputs', function(e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 13) {
var index = $('.inputs').index(this) + 1;
$('.inputs').eq(index).focus();
}
});
$(document).keypress(
function(event){
if (event.which == '13') {
event.preventDefault();
}
});
</script>
數據庫插入JSP
<%
try
{
String name=null;
String age=null;
String phone=null;
String email=null;
**This is parameters**
name=request.getParameter("name_1");
age=request.getParameter("age_1");
phone=request.getParameter("phone_1");
email=request.getParameter("email_1");
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/atm","root","root");
Statement st=con.createStatement();
int o=st.executeUpdate("INSERT INTO jquery values('"+name+"','"+age+"','"+phone+"','"+email+"')");
out.print("Success");
}
catch(Exception e)
{
System.out.println(e);
}
%>
請不要這樣做。這是一個不好的做法 - 編寫負責在UI級別上處理數據庫的代碼。它應該在服務器端。 –
請原諒我,如果我錯了,但不是JSP服務器端(I.e. ** S ** = _Server_)?或者客戶端是否存在不應該存在的方面? –
是的,你是對的。但無論如何,JSP負責UI。如果你想以良好的方式做到這一點,看看MVC模式 –