我有:
<tr>
<td>Product</td>
<!-- line below generates a select box with id="product" -->
<td id="product"><?=$this->formSelect($form->get('product'));?></td>
</tr>
<tr>
<td>Description</td>
<td><input type="text" name="Description" id="Description" /></td>
</tr>
<tr>
<td>Quantity</td>
<td><input type="text" name="Quantity" id="Quantity" /></td>
</tr>
<tr>
<td>Price</td>
<td><input type="text" name="Price" id="Price" /></td>
</tr>
当使用jQuery的onupdate
特性时,这与"产品"选择框的值变化事件有关,我如何更新描述,数量和价格字段。
我现在得到的是:
$("#product").change(function() {
$.ajax({
type : "POST",
url : "updatedescription.php",
data : 'product_id=' + $(this).val(),
cache : false,
success : function(html) {
$("#Description").html(html);
}
});
return false;
});
但是它只更新Description。
PHP代码function loadDescriptionByProduct()
{
$product = filter_var($_POST['product_id'], FILTER_SANITIZE_STRING);
$description = $this->repository->getDescriptionByProduct($product);
echo $description;
}
function getDescriptionByProduct(string $product)
{
$sql = "SELECT description FROM product where product=?";
$result = db_param_query($sql, $product);
$row = db_fetch_array($result);
$description = $row['description'];
return $description;
}
您需要调用单个资源,如getProductDetails.php
,并在那里获得与您想要的产品相关的所有信息。
function getProductDetails(string $product)
{
$sql = "SELECT price, description FROM product where product=?";
$result = db_param_query($sql, $product);
$row = db_fetch_array($result);
$response = array(
'price' => $row['price'],
'desc' => $row['description']
);
return json_encode($response); //return a json response.
}
Javascript $("#product").change(function() {
$.ajax({
type : "POST",
url : "getProductDetails.php",
data : 'product_id=' + $(this).val(),
cache : false,
success : function(response) {
var parsedResponse = $.parseJSON(response);
$("#Description").html(parsedResponse.desc);
// ...
$("#Price").html(parsedResponse.price);
}
});
return false;
});
另外,您可以使用Content-Type: application/json
响应头并通过使用dataType: 'json'
参数指示jQuery这是JSON。(并删除$.parseJSON()
)