我想从PHP返回多个数据(变量),而不是只返回一段html代码。
现在我得到了这个:
$.ajax({
url: "test.php",
cache: false
})
.done(function(html) {
$('video').attr('src', html);
});
但我希望能够做一些类似的事情:
$.ajax({
url: "test.php",
cache: false
})
.done(function(data) {
$('video').attr('src', data.videoUrl);
$('video').attr('poster', data.posterUrl);
});
在我的test.php中,我有以下内容:
$posterUrl = "thumbnail.png";
$videoUrl = "video.mp4";
echo $posterUrl;
echo $videoUrl;
我怎样才能完成这样的事情?
最简单的方法?JSON。
JavaScript:
$.ajax({
url: "test.php",
dataType: "JSONP"
}).done(function(json) {
$("video").attr("src", json.videoURL).attr("poster", json.posterURL);
});
PHP:
$output = array();
$output["posterURL"] = "poster.png";
$output["videoURL"] = "video.mp4";
echo json_encode($output);
您可能需要像这样对响应进行json_encode。
$response = array("videoUrl"=>"video.mp4","posterUrl"=>"video.mp4");
echo json_encode($response);
您可以返回JSON而不是字符串。
更多信息请点击此处:http://api.jquery.com/jQuery.getJSON/