[英]one ajax function runs on same form for multiple rows
我有一个ajax函数,该函数根据所选项目填充多个字段。 但我想增加一些行,以便人们可以选择更多相同形式的项目。 并尝试在其余行中运行相同的ajax函数,而不是仅在其中运行。 提交表单后,某些行可能会留空。
根据我的代码,在多行中填充多个字段的最佳方法是什么?
这是我的表单代码,现在只有一行供用户选择和插入,但我希望为用户提供约10行:
<form name="form" method="post" action="placedOrder.php">
<table width="70%" border="5" align="center">
<tr>
<th scope="row">Item Name</th>
<th scope="row">Item SKU</th>
<th scope="row">Quantity</th>
<th scope="row">Side Mark</th>
<th scope="row">Unit Price</th>
<th scope="row">Total Price</th>
</tr>
<tr>
<th scope="row">
<?php
include('connect.php');
$result = mysqli_query("SELECT description FROM products")
or die(mysqli_error());
print '<select name="description" id="description" value="description">';
print '<option value="" disabled selected>Please Select A Product</option>';
while ($info = mysqli_fetch_array($result))
{
$p = $info["description"];
$p = htmlspecialchars($p);
printf('<option value="%s">%s</option>', $p, $p);
}
print '</select>';
?>
</th>
<th scope="row">
<input name="sku_1" id="sku_1" readonly />
</th>
<th scope="row">
<input name="qty_1" />
</th>
<th scope="row">
<input name="note_1" />
</th>
<th scope="row">
<input name="uPrice_1" id="uPrice_1" readonly />
</th>
<th scope="row">
<input name="tPrice_1" id="tPrice_1" readonly />
</th>
</tr>
</table>
<input type="submit"/>
</form>
这是我的ajax函数:
<script type="text/javascript" language="javascript">
$(function () {
$('#description').change(function () {
$.ajax({
type: 'POST',
url: 'orderAuto.php',
data: {
description: $('#description').val()
},
dataType: 'json',
success: function (data) //on recieve of reply
{
var skuId = data[0];
var unitPrice = data[1];
$('#sku_1').val(skuId);
$('#uPrice_1').val(unitPrice);
}
});
});
});
</script>
这是我的PHP代码:
<?php
include('connect.php');
$p = mysqli_real_escape_string($_POST['description']);
$result = mysqli_query("SELECT sku_id, unit_price FROM products WHERE description= '".$p."'");
$array = mysqli_fetch_array($result);
echo json_encode($array);
?>
将AJAX方法声明为带有选择器数组的命名函数:这将允许您重用该函数并添加更多利用该函数的事件处理程序。
就像是:
function myAJAX(selectorArray) {
$.ajax({
//bunch of stuff
data: { description: $(this).val() },
// more stuff
success: function(data){
var skuId = data[0],
unitPrice = data[1];
selectorArray[0].val(skuId);
selectorArray[1].val(unitPrice);
}
});
}
另一种方法是为事件处理程序使用类选择器,并在其中选择目标元素。
$('mySelector').on('change', '#targetSelector', myAJAX(selectors));
这里的想法是在其中使用父选择器和其他选择器。
<div id="box">
<p id="text">Here is some text.</p>
<p>This is also some text</p>
</div>
在此示例HTML中,我们将div
作为父级,将p
作为子级。 因此,如果我们想使用事件处理程序(假设我们不需要任何其他参数),它将看起来像这样:
$('#box').on('change', '#text', myAJAX);
我们正在选择要异步更改的元素的父元素,并通过AJAX调用过滤到要更改的特定元素。 有关更多信息,请参见jQuery 文档以使用on
方法处理事件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.