简体   繁体   中英

How to fill the combobox from php with document ready function?

Here is the php code.In this code station name and ids and random passengers are produced.

<?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;
 }

 ?>

I want to fill the combobox with the produced station name and station ids when the page is loaded using document ready function.After that when the user selects a station with name and id, he can see how many passengers are there in that station and the ids of the passengers also should be returned from Station.php. Normally I have had this select options in html code, it just showing the stations not doing anything when choosing any of them.

<select name="selectStation" id="selectStation" ></select>

I tried the following;

     $(document).ready(function() {
      $.getJSON("Stations.php", function(jsonData){  

      $.each(jsonData, function(key,value) {   

      $('#selectStation')
     .append($("<option></option>")
     .attr("value",key)
     .text(value)); 

 });
});

});

I got the combobox values as object Object.Why does this happen? How can fill the combobox when the page is loaded, according to Stations.php.Thanks.Any response will be appreciated.

Okay, here's some sample code that will do what I think you want. Note: You still have to add an Event Listener to handle the change event of the select-box. I'll leave that to you.

File 1 : ajaxAfterLoad.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>

File 2 : makeJSON.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) );
?>

File 3 : AjaxRequest.js Download this file from http://ajaxtoolbox.com/request/source.php

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM