我是ajax的新手,我目前正在开发一个laravel项目。我的附加代码有问题,因为它在我的html标签上没有显示任何内容。这是我的javascript代码:
$(document).ready(function() {
$(document).on('change', '#product_category', function() {
var cat_id = $(this).val();
$.ajax({
type: 'get',
url: '{!! URL::to('findProductName ') !!}',
data: {
'id': cat_id
},
success: function(data) {
console.log('success');
console.log(data);
var op = " ";
op += '<option value="0" selected disabled>Choose Product</option>';
for (var i = 0; i < data.length; i++) {
op += '<option value="' + data[i].id + '">' + data[i].name + '</option>';
}
var div = $(this).parent();
div.find('.choice').html(" ");
div.find('.choice').append(op);
},
error: function() {
}
});
});
});
HTML:
<tr id="orig_field">
<td>
<select name="" class="form-control" id="product_category">
<option value="0" disabled="true" selected="true">Category...</option>
@foreach($category as $cat)
<option value="{{ $cat->id }}">{{ $cat->name }}</option>
@endforeach
</select>
</td>
<td>
<select name="" class="form-control" id="prod_name">
<option value="0" disabled="true" selected="true">Choose</option>
<div class="choice"></div>
</select>
</td>
<td id="getRequest"></td>
<td>
<input type="number" class="form-control" name="sale_qty[]" min="0">
</td>
<td></td>
</tr>
<tr id="copy_field"></tr>
我刚刚发布了这个帖子,但我对堆栈溢出很新,并没有提供全部细节。非常感谢帮助
答案 0 :(得分:0)
你不能在选择中有一个div。但您可以将选项附加到选择:
// this array emulates your response from the ajax call
var data = [
{ "id": 1, "name": "Product 1" },
{ "id": 2, "name": "Product 2" },
{ "id": 3, "name": "Product 3" },
{ "id": 4, "name": "Product 4" },
{ "id": 5, "name": "Product 5" },
],
products = $("select[name=prod_name]");
jQuery.each(data, function( index, value ) {
products.append('<option value="' + value.id + '">' + value.name + '</option>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#" method="post">
<select name="prod_name">
<option value="0" disabled="true" selected="true">Choose</option>
</select>
</form>