gpt4 book ai didi

javascript - 如何用json数据填充select?

转载 作者:行者123 更新时间:2023-12-01 01:21:14 25 4
gpt4 key购买 nike

我正在练习购物车列表,但无法填充我已经尝试过多次但没有成功的选择。任何指导将不胜感激。

PHP:

$get_cart =  mysqli_query($link,"SELECT cpro_id,cpro_name,cpro_price,cpro_qty FROM cart WHERE owner='$client'");
$rows = array();
while($r = mysqli_fetch_assoc($get_cart)) {
$rows[] = $r;
}
echo json_encode(array("status"=>"OK","data"=>$rows));
return true;

服务器响应:

{"status":"OK","data":[
{"cpro_id":"9","cpro_name":"Product1","cpro_price":"10.00","cpro_qty":"1"},
{"cpro_id":"10","cpro_name":"Product2","cpro_price":"10.00","cpro_qty":"1"},
{"cpro_id":"11","cpro_name":"Product3","cpro_price":"10.00","cpro_qty":"1"},
{"cpro_id":"12","cpro_name":"Product4","cpro_price":"10.00","cpro_qty":"1"},
{"cpro_id":"13","cpro_name":"Product5","cpro_price":"10.00","cpro_qty":"1"}
]}

JS/HTML:

<select name="info" size="1" id="info" style="display:block;width: 100%;">
<option selected value="cpro_id">cpro_name</option>
</select>
<script>
$(document).ready(function() {
$.ajax({
method: "POST",
dataType: "JSON",
data: {
action: 'getcart'
},
url: "api.php"
})
.done(function(cart) {
//fill list
});
});
</script>

最佳答案

您可以使用 $.each 轻松填充您的 json 数据,如下例所示:

let obj = {
"status": "OK",
"data": [{
"cpro_id": "9",
"cpro_name": "Product1",
"cpro_price": "10.00",
"cpro_qty": "1"
},
{
"cpro_id": "10",
"cpro_name": "Product2",
"cpro_price": "10.00",
"cpro_qty": "1"
},
{
"cpro_id": "11",
"cpro_name": "Product3",
"cpro_price": "10.00",
"cpro_qty": "1"
},
{
"cpro_id": "12",
"cpro_name": "Product4",
"cpro_price": "10.00",
"cpro_qty": "1"
},
{
"cpro_id": "13",
"cpro_name": "Product5",
"cpro_price": "10.00",
"cpro_qty": "1"
}
]
};

$.each(obj.data, function(i, v) {
$('#info').append('<option value="' + v.cpro_id + '">' + v.cpro_name + '</option>')
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="info" size="1" id="info" style="display:block;width: 100%;">
<option selected value="cpro_id">cpro_name</option>
</select>

在您的代码中:

$.ajax({
method: "POST",
dataType: "JSON",
data: {
action: 'getcart'
},
url: "api.php"
})
.done(function(cart) {
$.each(cart.data, function(i, v) {
$('#info').append('<option value="' + v.cpro_id + '">' + v.cpro_name + '</option>')
});
});

关于javascript - 如何用json数据填充select?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59692769/

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