gpt4 book ai didi

javascript - ajax 上的 get 函数内部出现未定义错误

转载 作者:行者123 更新时间:2023-12-02 18:04:36 26 4
gpt4 key购买 nike

美好的一天,我的 ajax 代码遇到了这个奇怪的问题,请看一下:

$(".productDropdown").bind("change", productDropdown);
function productDropdown(){

$.get('/api/productDropdown',
{ option: $(this).val() },
function(data) {

var parent = $(this).parents('tr');
var qty = $(parent).find('input.qty').val();
var price = $(parent).find('input.price').val();
var description = $(parent).find('textarea.description').val();

console.log(price+":"+qty+":"+description);

});

}

日志结果是:

undefined:undefined:undefined 

但是当我在 get 函数之外声明变量时,我可以获得正确的值。但我仍然无法将它们分配到文本框上。因为当我尝试放置时:

description.val(data.description);

在变量下面我收到此错误:

Uncaught TypeError: Cannot call method 'val' of undefined 

(这是一个外部js文件)

(已更新)

这是我的 HTML 文件:

<table id="tblContacts" class="table-responsive table table-striped table-bordered tablesorter table-hover col-lg-12">            
<thead>
<tr>
<th class="col-lg-3">Product Name</th>
<th class="col-lg-4">Description</th>
<th class="col-lg-1">Quantity</th>
<th class="col-lg-1">Price</th>
<th class="col-lg-3">Action</th>
</tr>
</thead>
<tbody>
<tr>
<td>

<script type="text/javascript">
var my_var = {"":"Please select","1":"Paracetamol","2":"Biogesic","3":"Bioflu","4":"Medicol"};
</script>

<select class="form-control productDropdown" placeholder="Company Name" id="productId" required="required" name="product[0][name]">
<option value="" selected="selected">Please select</option>
<option value="1">Paracetamol</option>
<option value="2">Biogesic</option>
<option value="3">Bioflu</option>
<option value="4">Medicol</option>
</select>
</td>
<td><textarea name='product[0][description]' class="form-control description" rows="1" required></textarea>
</td>
<td><input type='number' min="1" max="9999" name='product[0][quantity]' class="form-control qty" required value="52"></td>
<td><input type='number' min="0.5" max="9999" name='product[0][price]' class="form-control price" required/></td>
<td>
<a href="#" class="btnRemoveRow btn btn-danger">Remove</a>

</td>
</tr>

</tbody>
</table>

请有任何想法...我们将非常感谢您的帮助,非常感谢您的宝贵时间。

最佳答案

成功函数中的

$(this) 并不是您期望的那样。您需要在 $.get 之前定义一个变量,并在 success 函数中使用它:

$(".productDropdown").bind("change", productDropdown);

function productDropdown() {
var target = $(this);
$.get('/api/productDropdown', {
option: $(this).val()
}, function (data) {

var parent = target.parents('tr');
var qty = $(parent).find('input.qty').val();
var price = $(parent).find('input.price').val();
var description = $(parent).find('textarea.description').val();

console.log(price + ":" + qty + ":" + description);

});
}

关于javascript - ajax 上的 get 函数内部出现未定义错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20202633/

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