这是 php 代码。在此代码中生成站名和 ids 和随机乘客。
<?php
include_once('RestUtils.php');
include_once('Passengers.php');
class Station implements JsonSerializable
{
private $id;
private $name;
private $passengers;
public function __construct($id, $name)
{
$this->setId($id);
$this->setName($name);
$this->passengers = array();
}
//getters and setters
public function jsonSerialize()
{
$data = array();
$data['id'] = $this->id;
$data['name'] = $this->name;
$data['passengers'] = $this->passengers;
return $data;
}
}
$stations = generateStations();
$data = RestUtils::processRequest();
switch($data->getMethod())
{
// Get item
case 'get':
if(isset($data->getRequestVars()['stationId']))
{
// Prepare information for a specific station
$station = getStationWithId($stations, $data->getRequestVars()
['stationId']);
if($station != null)
{
echo RestUtils::sendResponse(200, json_encode($station),
'application/json');
}
else
{
echo RestUtils::sendResponse(404, 'Station not found!');
}
}
else
{
// Prepare station list
echo RestUtils::sendResponse(200, json_encode($stations),
'application/json');
}
break;
}
function generateStations()
{
$stations = array();
for($i = 1; $i <= 5; $i++)
{
$stations[] = new Station($i, 'İstasyon ' . $i);
$passengerIds = array();
foreach(generatePassengers() as $j)
{
$passengerIds[] = $j->getId();
}
$stations[$i - 1]->setPassengers($passengerIds);
}
return $stations;
}
function generatePassengers()
{
$passengers = array();
$numberOfPassengers = rand(0, 20);
for($i = 0; $i < $numberOfPassengers; $i++)
{
$from = rand(0, 5);
$to = rand(0, 5);
$arrivalTime = rand(0, 100);
$waitingTime = rand(0, 100);
$passengers[] = new Passenger($i, $from, $to, $arrivalTime, $waitingTime);
}
return $passengers;
}
function getStationWithId($stations, $id)
{
foreach ($stations as $i)
{
if($i->getId() == $id)
{
return $i;
}
}
return null;
}
?>
我想在使用文档准备功能加载页面时用生成的车站名称和车站 ID 填充组合框。之后,当用户选择一个带有名称和 ID 的车站时,他可以看到该车站有多少乘客以及乘客的 id 也应该从 Station.php 返回。通常我在 html 代码中有这个选择选项,它只是显示站在选择其中任何一个时没有做任何事情。
<select name="selectStation" id="selectStation" ></select>
我尝试了以下方法;
$(document).ready(function() {
$.getJSON("Stations.php", function(jsonData){
$.each(jsonData, function(key,value) {
$('#selectStation')
.append($("<option></option>")
.attr("value",key)
.text(value));
});
});
});
我将组合框值作为对象 Object。为什么会发生这种情况?根据 Stations.php.Thanks,如何在页面加载时填充组合框。任何回复将不胜感激。