我正试图从服务器8080端口上运行的服务中获取JSON对象。我已经实现了以下JavaScript和PHP代码来实现这一点:
JavaScript:
$.ajax({
type: 'GET',
url: "mediainfo.php?file="+stream_,
dataType: 'json',
success: play,
error: function( xhr, reply ) {
play({});
}
});
mediainfo.php:
<?php
$url = "http://localhost:8080/media_info/" . $_GET['file'];
echo file_get_contents($url);
但是,即使Ajax调用成功,它也不会调用回调。奇怪的是,如果失败(例如$url没有返回有效的JSON),它会调用回调。
我不知道出了什么问题。任何帮助都将不胜感激。
编辑:
回调函数:
var play = function( info ) {
if ( info.width && info.height ) {
while ( info.width < 640 ) {
info.width = Math.round( info.width * 1.5 );
info.height = Math.round( info.height * 1.5 );
}
while( info.width > 1024 ) {
info.width = Math.round( info.width / 2 );
info.height = Math.round( info.height / 2 );
}
}
var width = info && info.width || 640;
var height = info && info.height || 480;
var flashvars = {
file : stream,
streamer : "rtmp://myserver.com:1935/vodplayback",
'rtmp.tunneling' : false,
bufferlength : 5,
autostart : true
};
var paramObj = {allowfullscreen : "true", allowscriptaccess : "always"};
swfobject.embedSWF("http://myserver.com:8080/flu/jwplayer.swf", "videoplayer", width, height, "10.3", false, flashvars, paramObj, {id : "jwplayer", name : "jwplayer"});
}
medinfo.php的回复:
{"duration":69960.0,"width":720,"height":406}
因此,函数声明的顺序与Ajax调用有关。谁知道^^
在Ajax调用之后,我定义了回调函数。我把它们换了一下,现在效果很好。
感谢您的回复。
$.ajax({
url: 'test.php',
dataType: 'html',
data: { test: 'test' },
type: 'GET',
success: function( data ) {
console.log( 'success' );
$( '#div2' ).html( data );
},
error: function( xhr ) {
console.log( xhr.status );
}
});
或者像这个
<?php
$url = "http://localhost:8080/media_info/" . $_GET['file'];
echo json_encode( Array(
'data': file_get_contents( $url )
) );
?>
javascript
$.ajax({
url: 'test.php',
dataType: 'json',
data: { file: stream_ },
type: 'GET',
success: function( callback) {
console.log( 'success' );
$( '#div2' ).html( callback.data );
},
error: function( xhr ) {
console.log( xhr.status );
}
});