0

这是 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,如何在页面加载时填充组合框。任何回复将不胜感激。

4

1 回答 1

1

好的,这里有一些示例代码可以满足我的要求。注意:您仍然需要添加一个事件侦听器来处理选择框的更改事件。我会把它留给你。

文件 1ajaxAfterLoad.html

<!DOCTYPE html>
<html>
<head>
<script src="script/AjaxRequest.js"></script>
<script>
function byId(e){return document.getElementById(e);}
function newEl(tag){return document.createElement(tag);}
function newTxt(txt){return document.createTextNode(txt);}


window.addEventListener('load', mInit, false);

function mInit()
{
    AjaxRequest.get( { 'url':'makeJSON.php', 'onSuccess': onAjaxRequestDone } );
}

function makeSelectElementFromJSON(elemId, jsonText)
{
    var srcData = JSON.parse(jsonText);
    var result = newEl('select');
    result.setAttribute('id', elemId);
    var i, curOpt;
    for (i=0; i<srcData.length; i++)
    {
        curOpt = newEl('option');
        curOpt.setAttribute('value', srcData[i].value);
        curOpt.appendChild( newTxt( srcData[i].text ) );
        result.appendChild(curOpt);
    }
    return result;
}

function onAjaxRequestDone(req)
{
    var span = newEl('span');
    span.innerHTML = req.responseText;
    byId('rawOutput').innerHTML = req.responseText;

    byId('ajaxOutput').appendChild( makeSelectElementFromJSON('jsonSelectBox1', req.responseText) );
}
</script>
<style>
</style>
</head>
<body>
    <h2>Below will be loaded by ajax</h2>
    <div id='rawOutput'></div>
    <div id='ajaxOutput'></div>
</body>
</html>

文件 2makeJSON.php

<?php

    $resultList = null;

    for ($i=0; $i<10; $i++)
    {
        $curItem = null;
        $curItem->value = $i;
        $curItem->text = "Item " . ($i+1);
        $resultList[] = $curItem;
    }
    printf("%s", json_encode($resultList) );
?>

文件 3AjaxRequest.js从http://ajaxtoolbox.com/request/source.php 下载此文件

于 2013-04-10T15:25:10.777 回答