Используйте JSONP для возврата массива из PHP в JavaScript - PullRequest
0 голосов
/ 09 ноября 2010

Я пытаюсь использовать JSONP для возврата массива из PHP в JavaScript.Надеюсь, мой код продемонстрирует именно то, что я пытаюсь сделать, потому что я даже не уверен, как это выразить ...

Мой PHP-файл, порт 80, следовательно, необходимо использовать JSONP, а не JSON(Я уже пробовал) Я не уверен, правильно ли я формирую переменные $ _GET, я почти уверен, что это неправильно, и причиной этого является отсутствие знаний ...

<?php
$directory = './thumbnails/';

// create a handler to the directory
$dirhandler = opendir($directory);

// read all the files from directory
$nofiles=0;
while (false !== ($file = readdir($dirhandler))) {

// if $file isn't this directory or its parent 
//add to the $files array
        if ($file != '.' && $file != '..')
        { 
            $thumbs[$nofiles]= 'http://localhost:80/mapScripts/thumbnails/' . $file; 
            $nofiles++;               
        }   
}

//$i = rand(0, 3);


//$output = "{";
for($i=0; $i < 3; $i++){
$json[i] = json_encode($thumbs[$i]); 
$output = $output . $_GET['thumbnails' . $i]. "(".$json[i].")";
//$output = $output . "'thumb" . $i . "':'" . $thumbs[$i] . "',";
}

//$output = $output . "}";
//echo $_GET['thumbnails'] ."(".$json.")";

echo $output;

?>

Затем в JavaScript на порту 8080 (междоменный и да, он работал нормально, пока я не попытался использовать этот массив, а не просто передать один URL-адрес изображения), я хочу получить каждый URL-адрес изображения из массива PHP, чтобы я мог создавать значки с помощьюimage ..

function makeThumbs(data, layer){
                var icon = new OpenLayers.Icon(data);
                layer.addMarker(new OpenLayers.Marker(new OpenLayers.LonLat(93.9, 29.53).transform(new OpenLayers.Projection("EPSG:4326"), new OpenLayers.Projection("EPSG:900913")),icon));
                for(var m = 0; m < layer.markers.length; m++){
                    layer.markers[m].events.register("click", layer.markers[m], function clickIcon(e){alert("How are you?");});
                    $("[id$=innerImage]").css({"border-style":"solid","border-width":"3px","border-color": "white"});
                }
            }

            $.getJSON('http://localhost:80/mapScripts/getThumbs.php?thumbnails2=?', function(data) {makeThumbs(data, markers);});

снова URL, который я передаю методу $ .getJSON, также, вероятно, неверен.Мне нужно знать, как выбрать точный URL-адрес фотографии из передаваемого массива, а не все данные JSONP.

Я ценю ваше время и отзывы за помощь в этом.

elshae

1 Ответ

0 голосов
/ 10 ноября 2010

Я действительно нашел один способ сделать это .. Вот идет ..

<?php
$directory = './thumbnails/';

// create a handler to the directory
$dirhandler = opendir($directory);

// read all the files from directory
$nofiles=0;
while (false !== ($file = readdir($dirhandler))) {

// if $file isn't this directory or its parent 
//add to the $files array
        if ($file != '.' && $file != '..')
        { 
            $thumbs[$nofiles]= 'http://localhost:80/mapScripts/thumbnails/' . $file; 
            $nofiles++;               
        }   
}

//$i = rand(0, 3);


$output = $_GET['thumbnails'] . "({";
for($i=0; $i < 3; $i++){
//$json[i] = json_encode($thumbs[$i]); 
//$output = $output . $_GET['thumbnails' . $i]. "(".$json[i].")";
$output = $output . "'thumb" . $i . "':'" . $thumbs[$i] . "',";
}

$output = $output . "})";
//echo $_GET['thumbnails'] ."(".$json.")";

echo $output;

?>

Это выводит: ({'thumb0': 'http://localhost:80/mapScripts/thumbnails/Tibet2.jpeg','thumb1':'http://localhost:80/mapScripts/thumbnails/lhasa.jpeg','thumb2':'http://localhost:80/mapScripts/thumbnails/Tibet.jpg',})

Тогда в JavaScript я просто:

function makeThumbs(data, layer){
                alert("already Here "+ data);
                var icon = new OpenLayers.Icon(data);
                alert(icon.url);
                layer.addMarker(new OpenLayers.Marker(new OpenLayers.LonLat(93.9, 29.53).transform(new OpenLayers.Projection("EPSG:4326"), new OpenLayers.Projection("EPSG:900913")),icon));
                for(var m = 0; m < layer.markers.length; m++){
                    layer.markers[m].events.register("click", layer.markers[m], function clickIcon(e){alert("How are you?");});
                    $("[id$=innerImage]").css({"border-style":"solid","border-width":"3px","border-color": "white"});
                }
            }

            $.getJSON('http://localhost:80/mapScripts/getThumbs.php?thumbnails=?', function(data) {makeThumbs(data.thumb2, markers);});

Так что после переменной $ _GET вы можете поместить типичные данные JSON и извлечь их, как обычно (обратите внимание на data.thumb2 в JavaScript).

...