您好,我无法从通过ajax返回的以下数组中获取数据:
Array
(
[routes] => Array
(
[0] => Array
(
[route_id] => 4
[company_id] => 2
[from] => Soye
[to] => Martelange
[fare] => 98
[is_active] =>
)
[1] => Array
(
[route_id] => 9
[company_id] => 2
[from] => Auckland
[to] => Stevoort
[fare] => 65
[is_active] =>
)
[2] => Array
(
[route_id] => 11
[company_id] => 2
[from] => Bowden
[to] => Kessel
[fare] => 60
[is_active] =>
)
[3] => Array
(
[route_id] => 17
[company_id] => 2
[from] => Berg
[to] => Clearwater Municipal District
[fare] => 97
[is_active] =>
)
[4] => Array
(
[route_id] => 24
[company_id] => 2
[from] => Martelange
[to] => Soye
[fare] => 98
[is_active] =>
)
[5] => Array
(
[route_id] => 29
[company_id] => 2
[from] => Stevoort
[to] => Auckland
[fare] => 65
[is_active] =>
)
[6] => Array
(
[route_id] => 31
[company_id] => 2
[from] => Kessel
[to] => Bowden
[fare] => 60
[is_active] =>
)
[7] => Array
(
[route_id] => 37
[company_id] => 2
[from] => Clearwater Municipal District
[to] => Berg
[fare] => 97
[is_active] =>
)
)
)
这是我的javascript:
var data = {id:id}; //Array
$.ajax({
url : url+"ticketinfo/routes",
type: "POST",
data : data,
success: function(data, textStatus, jqXHR)
{
var jsonArray = data.routes;
var options = $("#options");
$.each(jsonArray , function(index, data) {
//adds all this values fron the array ,only from and to
options.append($("<option/>").text(data.from + " / " + data.from));
});
},
error: function (jqXHR, textStatus, errorThrown)
{
}
});
由于麻烦,我的意思是我不知道如何,我在这里尝试了几个例子,但没有一个适合我。我想要做的就是在数组中获取这两个字段:from和to并使用该数据动态地使用jquery动态填充两个select控件。如果有人可以帮我解决这个问题,我将非常感激。先感谢您。 :)
答案 0 :(得分:0)
所以显然这一切都与json数组的编码和解码有关。 Csdtestings回答的原因不起作用是因为他在他的例子中使用的数组不是我认为的json编码对象数组。无论如何,我尝试在返回的数组上使用json.parse,摆脱了错误,但后来我有另一个问题,即数组元素全部显示为“[object] [object]”。因此,我发现它可能与已编码的数组类型有关。所以我回到我的PHP并改变了这个:
$data = $this->route->get_routes_by_company($company_id); //using codeigniter framework
echo json_encode($data);
对此:
$data = $this->route->get_routes_by_company($company_id); //using codeigniter framework
foreach ($data as $row)
{
$result = array($row['from'], $row['to']);
}
echo json_encode($result);
之后我只是将我的javascript更改为了这个并且瞧它工作了:
$.ajax({
type: "POST",
url: url+"ticketinfo/routes",
data: {
'id' : id
},
dataType: "json",
success: function (response) {
if (response.length > 0)
{
$.each(response, function(index, element) {
$('#From').append("<option value='" + element[0] + "'>" + element[0] + "</option>");
$('#To').append("<option value='" + element[1] + "'>" + element[1] + "</option>");
});
}
}
});
答案 1 :(得分:-1)
我就是这样做的,您是否尝试过以下方法检查输出到控制台作为测试结果?
var routes = data.routes
for(var i = 0; i < routes.length; i++){
console.log(routes[i].to);
console.log(routes[i].from);
}
答案 2 :(得分:-1)
试试这个:
var selectData1 = "";
var selectData2 = "";
routes.each(function(index,options)
{
selectData1 += '<option>' + $(this)[0].from + '</option>';
selectData2 += '<option>' + $(this)[0].to + '</option>';
});
$("#select1ID").html(selectData1);
$("#select2ID").html(selectData2);
我没有尝试过,所以期待一些语法错误,但这应该可以完成你需要的工作。