..试着这种方式..
链接到另一个页面对我来说并不是很有用..我已经查看了大部分页面并且无法根据我的需要调整它们。
我不熟悉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({ ... })
。