Ajax返回数据与文本字段的数据比较不起作用?



在ajax返回数据中,它将返回如下所示的用户记录:

Array(6)
0:{_id: 1, provider: "abc", time: null, email_id: "abc@gmail.com"}
1:{_id: 2, provider: "abc", time: null, email_id: "abcd@gmail.com"}
2:{_id: 3, provider: "abc", time: null, email_id: "abcde@gmail.com"}
3:{_id: 4, provider: "xyz", time: null, email_id: "xyz@gmail.com"}
4:{_id: 5, provider: "dea", time: null, email_id: "dea@gmail.com"}
5:{_id: 6, provider: "bcmc", time: null, email_id: "bcmc@abc.com"}

上面的数据由 ajax 返回,使用循环我正在处理它并将其与文本字段数据进行比较,可以在下面给出的if else条件下:-

法典

value_field = $('#provider_field').val();
$.ajax({
url:"/api/v1/provider",
type: "GET",
dataType: 'json',
async: false,
success: function(response){
console.log(response.response)
for (var i = 0; i < response.response.data.length; i++) {
console.log(response.response.data[i].provider === value_field);
if (response.response.data[i].provider === value_field){
$('#search').append("<option value = "+response.response.data[i]._id+">"+response.response.data[i].provider+"</option>");
counter = 1;
}else{
counter = 0;
//here I want to remove
}
}
}
});

.HTML

<input type="text" name="provider_field" id="provider_field" value="" placeholder="Enter the Provider name">
<select id= "search">
</select>

问题

  • 如果该项目具有与value_field相同的提供程序,我想将一个附加到#search。 如果它与任何提供者或错误的提供者不匹配,我想清空选择选项。

帮我解决这个问题。

你已经添加了中断;语句在你的如果否则是问题。

只需从 if else 语句中删除 break 语句

您可以清除获取ajax响应的所有选项,请检查以下更新代码。

$.ajax({
url:"/api/v1/provider",
type: "GET",
dataType: 'json',
async: false,
success: function(response){
console.log(response.response);
//Below line will clear all the previous options
$('#search').find('option').remove();
for (var i = 0; i < response.response.data.length; i++) {
console.log(response.response.data[i].provider === value_field);
if (response.response.data[i].provider === value_field){
$('#search').append("<option value = "+response.response.data[i]._id+">"+response.response.data[i].provider+"</option>");
//break;
}
}
}
});
value_field = $('#provider_field').val();
$.ajax({
url: "/api/v1/provider",
type: "GET",
dataType: 'json',
async: false,
success: function(response) {
console.log(response.response)
for (var i = 0; i < response.response.data.length; i++) {
console.log(response.response.data[i].provider === value_field);
if (response.response.data[i].provider === value_field) {
$('#search').append("<option value = " + response.response.data[i]._id + ">" + response.response.data[i].provider + "</option>");
counter = 1;
} else {
counter = 0;
//here I want to remove
$("#search option[value='" + response.response.data[i]._id + "']").remove();
} // end of else
}// end of id
}// end of for
});// end of ajax

相关内容

  • 没有找到相关文章

最新更新