我有以下html
<select id="options" title="prd_name1" name="options" onblur="getpricefromselect(this);" onchange="getpricefromselect(this);"></select>
和
<input type="text" id="prd_price" title="prd_price1" name="prd_price">
我从系统数据库动态更新了<select></select>
一些产品及其各自的ID。我编写了一个JQuery / Javascript函数,它假设使用$ .ajax()将选择菜单中的产品ID发送到php页面,并从数据库中获取相应的价格并用该价格填充<input>
。
我的jQuery如下:
function getpricefromselect(x){
var value=$(x).val();
var title=$(x).attr('title');
if(title.length == 9){
var len=Number((title).substr(-1,1));
if(value.length>0){
$.ajax({
type:'POST',
url:'getpricefromselect.php',
data:{productid: value},
success:function(data){
$("[title=prd_price"+len+"]").val(data).show();
}
})
}
}
};
“getpricefromselect.php”中的php如下:
$productid="";
$Price="";
$productid=$_POST["productid"];
$selectProduct="SELECT InventoryProductPrice FROM InventoryProductsList WHERE InventoryProductID = '{$productid}';";
$selectProduct_query = mysqli_query($connection, $selectProduct);
if(!$selectProduct_query){
die ("Database query for selecting Product Price failed.");
}
while ($selectProduct_array = mysqli_fetch_assoc($selectProduct_query)){
$Price= $selectProduct_array["InventoryProductPrice"];
}
echo $Price;
问题是,当我从php文件回显$ Price时,jQuery $ .ajax()用空白项填充<input>
但是如果我回显$ productid,那么它会填充<input>
的精确值的productid。我的产品ID对于每个产品都是唯一的,当我在与javascript相同的页面上调用相同的php函数时,它会返回准确的价格。任何人都可以告诉我为什么$ .ajax()得到一个空白项目,如果$ Price从php回应,如果$ productid从php回显,它不会给出一个空白项目。
如果我手动将实际产品ID添加到php文件中,则由PHP回显的$ Price是准确的。如果它是通过POST从$ .ajax()发送的,那么它似乎没有被php准确运行。
答案 0 :(得分:0)
如果您使用开发人员控制台查看查询带来的答案或者ajax请求有什么问题,那将是件好事。
另一方面,您可以尝试这样
$(function(){
$("#options").change(function()){
getpricefromselect($(this).val());
});
})
function getpricefromselect(x){
var obj = {
productid:x
}
$.post('getpricefromselect.php',obj)
.done(function(resp){
if(resp){
$("#prd_price").val(resp)
}
})
.fail(function(err){
})
};