我想制作一个包含几个输入字段的表单。在这些字段中输入内容时,必须出现一个下拉列表,其中包含 MySQL 数据库中的匹配记录。以下是 Javascript 代码:
<script type="text/javascript">
$(function() {
$("#sampleprep, #quantity, #sampletype, #organism").autocomplete({
response: function(event, ui) {
try {
// ui.content is the array that's about to be sent to the response callback.
if (ui.content.length === 0) {
$("#"+event.target.id+"-empty-message").text("No results found");
} else {
$("#"+event.target.id+"-empty-message").empty();
//$("#"+event.target.id+"-empty-message").text(event.target.id);
}
} catch(err) {
error = "Error 1: "+err.message;
alert(error);
}
},
source: function(request, response) {
try {
var target_id = "sampletype"; <====
$.ajax({
url: "list_"+target_id+".php", <====
dataType: "json",
data: {
term : request.term
},
success: function(data) {
response(data);
}
});
} catch(err) {
error = "Error 2: "+err.message;
alert(error);
}
},
minlength: 1
});
});
</script>
如您所见,有 4 个输入字段使用此代码:
- sample 准备
- 数量
- 样本类型
- 有机体
每个输入字段对应于它自己的数据库表。我制作了 4 个 PHP 文件来获取匹配的数据。文件名是:
- list_sampleprep.php
- list_quantity.php
- list_sampletype.php
- list_organism.php
我的问题由箭头 <====
指示。现在,url 固定为 list_sampletype.php
。我想让这个动态化,但我不知道如何将输入字段的 id 获取到 ajax 调用中。我试过event.target.id
,它在第一个函数以及其他一些函数中工作,但没有返回我想要的内容。
最佳答案
你能尝试这样的事情吗:
<script type="text/javascript">
$(function() {
$(".ajax_getid_").each(function () {
(function ($this) {
$this.autocomplete({
response: function(event, ui) {
try {
// ui.content is the array that's about to be sent to the response callback.
if (ui.content.length === 0) {
$("#"+event.target.id+"-empty-message").text("No results found");
} else {
$("#"+event.target.id+"-empty-message").empty();
//$("#"+event.target.id+"-empty-message").text(event.target.id);
}
} catch(err) {
error = "Error 1: "+err.message;
alert(error);
}
},
source: function(request, response) {
try {
var target_id = "sampletype"; <====
$.ajax({
url: "list_"+$this.attr('id')+".php", <====
dataType: "json",
data: {
term : request.term
},
success: function(data) {
response(data);
}
});
} catch(err) {
error = "Error 2: "+err.message;
alert(error);
}
},
minlength: 1
});
})($(this));
});
});
</script>
为了解释:对于每个元素,您将执行相同的函数,并且将使用所选元素的 ID。
关于Javascript 元素 id 到 AJAX url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22991164/