[英]How can I return a PHP array to the javascript function that called it
..試着這種方式..
鏈接到另一個頁面對我來說並不是很有用..我已經查看了大部分頁面並且無法根據我的需要調整它們。
我不熟悉ajax或jQuery。
我可以真正使用一些幫助,詳細解釋這個特定問題的代碼示例。 提前致謝..
我有這段代碼叫做:JSON_generator.php
<?php
require_once 'EasyWebFetch.php';
$callback = isset($_GET['callback']) ? $_GET['callback'] : 'mymap.weatherhandler';
$station = isset($_GET['rid']) ? $_GET['rid'] : 'FWS';
$product = isset($_GET['product']) ? $_GET['product'] : 'NCR';
$nframes = isset($_GET['frames']) ? $_GET['frames'] : 10;
if (strlen($product) != 3 || strlen($station) != 3) { exit; }
// fetch directory listing
$wf = new EasyWebFetch;
if (!$wf->get("http://radar.weather.gov/ridge/RadarImg/$product/$station/")) {
print $wf->getErrorMessage();
exit;
}
$page = $wf->getContents();
// echo $page."\n\n";
$size = preg_match_all( "/href=\"({$station}[\d_]+{$product}\.gif)\"/" , $page, $match);
$files = $match[1];
$nframes = min(count($files), $nframes);
$files = array_slice($files, -$nframes);
echo $callback."\n(\n{\ndirectory:\n[\n";
for ($i=0; $i < $nframes; $i++) {
echo "\"ridge/RadarImg/$product/$station/$files[$i]\",\n";
}
echo "]\n}\n)\n;"
?>
從這樣的命令行調用時......
http://example.com/mypath/JSON_generator.php?&?callback=CallBack&product=NCR&rid=JAX&frames=5
但我真正需要的是從一開始調用php的javascript函數中獲取那些.gif路徑/文件/名稱。**它們需要作為數組中的項目來訪問。
我無法弄清楚javascript函數調用這樣做..
..這樣的事情,但顯然不是這個..
function Feed (whichproduct, whichsite) {
var filelist = [];
var siteimages = filelist("http://example.com/mypath/JSON_generator.php?&product=whichproduct&rid=whichsite&frames=5");
..then..
//alert (filelist [1]); .. should return something like "ridge/RadarImg/NCR/JAX/JAX_20130128_2354_NCR.gif"
}
顯然,我是初學者,所以完整的答案對我來說比對代碼片段更有價值。
底線:
我需要一個javascript函數,可以從php腳本中提取每個.gif名稱並將它們帶回到javascript“var”中,我可以在html文件的其他地方使用它。
謝謝,丹尼斯
編輯..編輯刪除..想出來..
我最初會回答使用jQuery ,因為這會讓事情變得非常簡單,但我會在一段時間內使用vanilla Javascript實現更新。
在Feed
函數中,使用jQuery方便的$.ajax
方法進行AJAX調用。
function Feed (whichproduct, whichsite) {
$.ajax({
"url": "http://mysite.com/mypath/JSON_generator.php?&product=whichproduct&rid=whichsite&frames=5"
"type": "GET",
"dataType": "json",
"success": function( data, status, xhr ){
alert( data[1] );
}
});
}
在你的PHP中,在格式良好的PHP數組上使用json_encode
(只需推送到array()
而不是直接回顯網址和逗號等)。
最后, print json_encode( $yourArray )
。
而不是在這里復制(廣泛的)javascript,我只是鏈接到@Richard H的一個很好的答案 。 希望如果您不使用jQuery,這會有所幫助!
json_encode($array);
是要走的路。 json_encode
函數編寫一個JSON對象供您將其傳遞給Javascript。
然后在Javascript中你可以安裝(如果你還沒有使用它)jQuery並用jQuery.parseJSON()解析JSON字符串,它返回一個准備使用的javascript對象。
為了補充已經發布的答案,這里有兩個問題:
{ ... }
,模仿JSON的數據結構,並且用於解析; JSONP有一個函數調用,它被執行: callback({ ... })
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.