我正在嘗試使用Jquery向產品和價格添加帶有訂單的動態行。問題是我需要從mysql動態填充產品下拉菜單。行正確添加。我遇到的唯一問題是,下拉菜單隻有一個選項,該選項顯示「未定義」。當試圖動態填充選擇列表時,Json結果爲「undefined」
編輯1:我改變了PHP代碼。我認爲它現在格式正確,但我仍然在我的選擇列表中顯示「未定義」。
編輯2:我測試了PHP,並且出現了一些錯誤。現在,PHP可以自行完成工作,並返回以下json編碼數組,但是當我試圖將它拖入我的jquery腳本時,它仍然返回「未定義」結果。 :
[{"product":"wedding 4","price":"400.00","id":"9"},
{"product":"wedding 2 ","price":"400.00","id":"8"},
{"product":"Wedding 1","price":"4000.00","id":"1"},
{"product":"potato","price":"50.00","id":"6"},
{"product":"Event","price":"3000.00","id":"5"},
{"product":"alligator","price":"800.00","id":"7"}]
的jQuery:
var count = 0;
$(document).ready(function(){
$('p#add_field').click(function(){
count += 1;
$('#addingContainer').append('<strong>Link #' + count + '</strong><br />' + '<label>Product or Service</label><select id="product_' + count + '" name="products[]'+ '" >');
$.get('includes/productrow.php', function(data){
$('#product_' + count + '').append('<option value=' + data.product_id + ' data-price=' + data.price + '>' + data.product +'</option>');
});
$('#addingContainer').append('</select> <label>Price</label><input type="text" id="price_' + count + '" name="prices[]' + '" class="price" >');
});
productrow.php
<?php
$productSql = "SELECT product_id, product, price FROM products WHERE compid = '$compid' ORDER BY product desc";
$productResult = mysql_query($productSql, $link);
while($productRow = mysql_fetch_array($productResult)){
$final_array[] = array("product" => $productRow['product'], "price" => $productRow['price'], "id" => $productRow['id']);
};
echo json_encode($final_array);
?>
**免責聲明,我知道我應該使用PDO,一旦該項目完成後,我會開始使用它。
你應該既不是使用PHP-MySQL或PHP-MySQLi,它們現在都不好用,現在它已被棄用,並將在下一個版本 – engma 2014-09-11 13:39:56
@ Developer106中丟棄。您認爲'mysqli'擴展名被棄用的原因是什麼? – 2014-09-11 13:45:15
我不完全瞭解你的用例。如果你想在頁面加載時動態填充下拉列表,那麼不需要javascript/jQuery來完成這項工作。您是否在頁面加載後嘗試向下拉菜單中添加其他選項? – 2014-09-11 13:46:52