【发布时间】:2019-02-05 15:00:45
【问题描述】:
我有一些 javascript 接受用户输入,通过 ajax 使用该输入查询端点,并从结果中返回一个字段作为附加 <option> 到 datalist。这工作正常,我在选项列表中准确地看到了我需要的内容。
我的下一部分工作是,当我单击选项时,我希望对象中与其相关的其他字段填充表单输入的值。我已经把这一切都安排好了,但是当我点击一个项目时,它说result is not defined
在这一行:
$("#groupName").val(result[$(foundOption).attr('srindex')]._source.name);
所以我的选项是正确的,当我单击一个选项时,它会在控制台中反映单击的选项。问题是我显然没有正确地将结果传递给我的else if。
我的 _source 的层次结构是正确的,但我只是不知道如何更改 .val 参数以获取正确的值。
有什么想法吗?
$('#productInput').on('input', function () {
let _this = $(this);
let foundOption;
let optSelector = `option[value='${_this.val()}']`;
if (_this.val() === '') {
return;
} else if ((foundOption = $('#returnedProducts').find(optSelector)).length) {
console.log(optSelector); //this prints the option[value] of the clicked value as it should
$("#groupName").val(result[$(foundOption).attr('srindex')]._source.name);
$("#groupNum").val(result[$(foundOption).attr('srindex')]._source.code);
} else {
const searchResult = $(this).val();
$.ajax({ url: '/account/autocomplete',
data: {
search_result:searchResult
},
"_token": "{{ csrf_token() }}",
type: "POST",
success: function (response) {
console.log(response);
console.log(searchResult);
$("#returnedProducts").empty();
let result = response.hits.hits;
console.log(result);
for(let i = 0; i < result.length; i++) {
$("#returnedProducts").append("<option srindex=" + [i] + " value=" + result[i]._source.name + ">" + result[i]._source.name + "</option>");
}
}
});
}
});
更新: 我的对象看起来像这样
hits
hits
_source
name
code
【问题讨论】:
-
请尝试给我们一个可以重现您的问题的实时工作简单。
-
是的,检查我的答案
-
我给了你一个带有 /8 的小提琴的更新链接。它确实有_source。但同样,从我的 json 中获取值不是问题,它是将值放入另一个输入中。检查上面以 /8 结尾的我给你的链接
-
@ZakariaAcharki 你看到我下面的评论了吗?这在小提琴中有效,但我的“结果”是在我的代码中的 ajax 成功中定义的,所以这仍然不起作用。我可以将它从我的 ajax 传递给我的 if else
标签: javascript html json ajax