我将一个全局变量 (var arrDatas = []) 声明为一个数组,以便它可以从 $.get 方法的响应中获取值,但它没有任何值。
servlet 的响应将是“name1,abc@email.com;name2,def@email.com;name3,ghj@email.com;.....”
我的脚本:
<script type="text/javascript">
var arrDatas = [];
$(document).ready(function() {
$('#lecturerName').autocomplete({
source : function(request, response) {
var value = $('#lecturerName').val();
$.get('getLecturer', {
keyWordLN : value
}, function(responseText) {
**arrDatas = responseText.split(";");**
var arrName = [];
for ( var i = 0; i < arrDatas.length; i++) {
tem = [];
tem = arrDatas[i].split(",");
arrName[i] = tem[0];
}
response(arrName);
});
}
});
});
$.fn.pressEnter = function(fn) {
return this.each(function() {
$(this).bind('enterPress', fn);
$(this).keyup(function(e) {
if (e.keyCode == 13) {
$(this).trigger("enterPress");
}
});
});
};
$(document).ready(function() {
$('#lecturerName').pressEnter(function() {
name = $('#lecturerName').val();
email = "Chua lay duoc email";
for ( var i = 0; i < arrDatas.length; i++) {
if (arrDatas[i].indexOf(name) > 6) {
tem = [];
tem = arrDatas[i].split(",");
email = tem[1];
}
}
var $ulList = $('#selectedEmails');
value = '<li><div class="vT">'+ name+ '</div><div class="vM"></div><input type="hidden" name="txtToEmail" value="'+email+'"></li>';
$('<li>').text(value).appendTo($ulList);
});
});
</script>
还有我的jsp页面:
<tr>
<td>Người nhận</td>
<td colspan="1"><input type="text" id="lecturerName" size="26">
</td>
<td>
<ul class="menu-bar">
<li><a href="1">Home</a>
<ul id="selectedEmails">
<li>
<div class="vT">Name</div>
<div class="vM"></div>
<input type="hidden" name="txtToEmail" value="email">
</li>
</ul>
</li>
</ul>
</td>
</tr>
我的小服务程序:
@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
try {
String key = request.getParameter("keyWordLN");
Connection cnn = XJdbc.getConnection();
String sql = "SELECT Name, Emails FROM lecturers WHERE Name LIKE '%"+key+"%'";
Statement stm = cnn.createStatement();
ResultSet rs = stm.executeQuery(sql);
String result = "";
while (rs.next()) {
result = result + rs.getString("Name") + "," + rs.getString("Emails")+";";
}
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
response.getWriter().print(result);
cnn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
请帮助我知道为什么我的全局变量“arrDatas”没有任何价值。非常感谢 :)