..将以另一种方式尝试..
链接到另一个页面对我来说并不是很有用..我已经查看了大部分内容,但无法根据我的需要调整它们。
我不熟悉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
但我真正需要的是拥有那些.gif路径/文件/名称&#34;可用&#34;从一开始调用php的javascript函数。**它们需要作为数组中的项目访问。
我无法弄清楚要执行此操作的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&#34; var&#34;我可以在html文件的其他地方使用。
谢谢, 丹尼斯
编辑..编辑删除..想出来..
答案 0 :(得分:2)
我最初会使用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,而只是链接到一个不错的SO answer by @Richard H。希望如果您不使用jQuery会有所帮助!
答案 1 :(得分:0)
json_encode($array);
是要走的路。 json_encode
函数为您编写JSON对象以将其传递给Javascript。
然后在Javascript中你可以安装(如果你还没有使用它)jQuery并用jQuery.parseJSON()解析JSON字符串,它返回一个可以使用的javascript对象。
答案 2 :(得分:0)
为了补充已经发布的答案,这里有两个问题:
{ ... }
,模仿JSON的数据结构,并且用于解析; JSONP有一个函数调用,用于执行:callback({ ... })
。