【问题标题】:Populate select box with json data from laravel db query使用来自 laravel db 查询的 json 数据填充选择框
【发布时间】:2015-09-27 16:09:54
【问题描述】:

我有一个 html 选择框,需要使用 jquery ajax 填充来自 php (Laravel) 数据库查询的选择选项。我尝试了很多方法但没有结果,我只得到“未定义”的结果。 Laravel 脚本:

public function loturi($articol) {
$loturi = DB::select("select mgla_lotto from MG_V_DispoLottiBarcode d
join MG_AnaArt art on art.MGAA_Id = d.MGAA_Id join MG_LottiAnag  l on         
l.MGLA_Id = d.MGLA_Id where MGAA_MBDC_Classe IN ('SEM','FIN') and mbmg_id = 55 
and mgaa_matricola in (select  child.MGAA_Matricola component
from DB_Legami join MG_AnaArt  child on child.MGAA_Id = DBLG_Com_MGAA_Id
join MG_AnaArt  p on p.MGAA_Id = DBLG_MGAA_Id
where p.MGAA_Matricola = '$articol')  and mgla_datacreazione > '2014-01-01'
group by mgla_lotto having sum(dispo) > 0");
return compact('loturi');
}

结果是这样的:

{"loturi":[{"mgla_lotto":"1282\/15"},{"mgla_lotto":"1316\/15"},{"mgla_lotto":"1339\/15"},{"mgla_lotto":"1349\/15"},{"mgla_lotto":"1354\/15"},{"mgla_lotto":"1404\/15"},{"mgla_lotto":"1405\/15"},{"mgla_lotto":"1412\/15"}]}

jquery 脚本是这样的:

$(document).ready(function() {
$("#cod").change(function(){
var cod_articol = $("#cod").val();
$.ajax ({
url: "/internal/" + cod_articol ,
datatype: "json",
success: function(data) {
$.each(data, function(value){
$("#lot").append('<option id="' + value.index + '">' + value.name +   
'</option>');
      })
     }
   });
 });
});

【问题讨论】:

  • 你想要 1282 作为索引和 15 作为来自 1282/15 的名称吗?

标签: php jquery html json laravel-5


【解决方案1】:

您好,这是您的答案。

改变

$.each(data, function(value){

$.each(data.loturi, function(value){

并使用以下语法

$.each(data.loturi, function( index, value ){
    $("#lot").append('<option value="' + index + '">' + value.mgla_lotto  + '</option>');
}

转到链接查看我为您制作的示例。

https://jsfiddle.net/ovht7fkh/2/

【讨论】:

  • 我似乎越来越近了,现在我得到了一个等于查询结果数量的选择选项列表,但它们都是 [object Object]
  • 请查看编辑后的答案。您的代码有解决方案。
  • 如果它适合您,您会欣赏/接受答案吗?
  • 在option里面使用id属性也没用
猜你喜欢
  • 1970-01-01
  • 2018-09-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多