duanjue9296 2013-04-10 13:25
浏览 31
已采纳

如何使用文档就绪函数从php填充组合框?

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.

  • 写回答

1条回答 默认 最新

  • dongtuan1980 2013-04-10 15:25
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 雷达辐射源信号参考模型
  • ¥15 html+css+js如何实现这样子的效果?
  • ¥15 STM32单片机自主设计
  • ¥15 如何在node.js中或者java中给wav格式的音频编码成sil格式呢
  • ¥15 不小心不正规的开发公司导致不给我们y码,
  • ¥15 我的代码无法在vc++中运行呀,错误很多
  • ¥50 求一个win系统下运行的可自动抓取arm64架构deb安装包和其依赖包的软件。
  • ¥60 fail to initialize keyboard hotkeys through kernel.0000000000
  • ¥30 ppOCRLabel导出识别结果失败
  • ¥15 Centos7 / PETGEM