gpt4 book ai didi

javascript - 将数据从 ajax success 传递到外部 else/if 语句

转载 作者:行者123 更新时间:2023-12-03 01:13:55 24 4
gpt4 key购买 nike

我在从 ajax 成功函数获取适当的结果并将其传递给要使用的外部函数时遇到问题。

我目前正在接受用户输入,通过 ajax 查询数据源并返回对象,效果很好。我将结果附加到也有效的选项列表中。但是,当我单击该对象时,我想将与该对象关联的数据传递到 ajax 调用之外的 if/else 中的以下行:

$("#groupName").val(result[$(foundOption).attr('srindex')]._source.name);

所以我的选项是正确的,当我单击一个选项时,它会在控制台中反射(reflect)单击的选项。问题是我显然没有正确地将结果传递到我的 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

最佳答案

您可以将 input#groupName 的值附加到 _this.val()。另请注意 (foundOption = $('#returnedProducts').find(optSelector)).length 此代码段不会进行任何条件检查,而只是分配一个值

$('#productInput').on('input', function() {
let _this = $(this);
let foundOption;
let optSelector = `option[value='${_this.val()}']`;
if (_this.val() === '') {
return;
} else if ($('#returnedProducts').find(optSelector).length) {
$("#groupName").val(_this.val());
} else {

const searchResult = $(this).val();
$("#returnedProducts").empty();
var result = [{
_source: {
"name": "cat",
},

}, {
_source: {
"name": "cat1",
},

}, {
_source: {
"name": "cat2",
},

}, {
_source: {
"name": "cat33",
},

}];
for (let i = 0; i < result.length; i++) {
$("#returnedProducts").append("<option srindex=" + [i] + " value=" + result[i]._source.name + ">" + result[i]._source.name + "</option>");

}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="productInput" list="returnedProducts">
<datalist id="returnedProducts"></datalist>
<input id="groupName">

关于javascript - 将数据从 ajax success 传递到外部 else/if 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52103579/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com