我有一个 MVC 应用程序,它使用链接 1 中的自动完成功能.然后,为了能够格式化显示,我用这个 JSON 模式传递了一个复杂的 JSON 对象:
{
"name": "searchResults",
"properties": {
"Id": {
"type": "number",
"description": "Table.ID, maps to value",
"required": true
},
"Name": {
"type": "string",
"description": "Display name, maps to label",
"required": true
},
"Type": {
"type": "number",
"description": "Table selector (enum)",
"required": true
}
}
}
问题是我不能在 $.ajax
函数中使用 $(this)
。我尝试使用上下文,但它不起作用。我一直收到 “SyntaxError: Unexpected token <”。这是 JavaScript 代码:
$(function () {
$('*[data-autocomplete-url]').each(function () {
$(this).autocomplete({
source: function (request, response) {
$.ajax({
// THIS WORKS!
//url: $('*[data-autocomplete-url]').data('autocomplete-url'),
// THIS DOESN'T WORK!
url: $(this).data('autocomplete-url'),
dataType: "json",
contentType: 'application/json, charset=utf-8',
data: {
token: $("#tags").val()
},
success: function (data) {
response($.map(data, function (item) {
return {
label: item.Name,
value: item.Id
};
}));
},
error: function (xhr, status, error) {
alert(error);
}
});
},
select: function (event, ui) {
$("#tags").val(ui.item.label);
$("#tagsId").val(ui.item.value);
event.preventDefault();
},
focus: function (event, ui) {
$("#tags").val(ui.item.label);
event.preventDefault();
},
minLength: 3
});
});
});
这是 Razor 片段:
<div class="ui-widget">
<label for="tags">Tags: </label>
<input id="tags" data-autocomplete-url="@Url.Action("Search", "Search")" />
<input id="tagsId" hidden="hidden" />
</div>
有没有办法使用 $(this)
来获取负责触发操作的特定自动完成元素?
引用资料:
最佳答案
在 ajax 函数中 this
不起作用,因为它没有元素引用的范围。
在发出 ajax 请求之前,您需要存储一份副本:
var url = $(this).data('autocomplete-url');
并在 ajax 调用中使用该变量:
url:url
关于javascript - jQuery 自动完成在 $.ajax 中找不到 $(this),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23680938/