Php功能:
public function getThreadsbyNumber($number) {
$result = mysql_query("SELECT * FROM `threads` LIMIT $number");
while ($fetch = mysql_fetch_array($result)) {
$threads[] = $fetch;
}
return $threads;
}
Ajax url文件:
require_once '../Classes/MainController.php';
$mc = MainController::getInstance();
$result = $mc->getThreadsbyNumber(5);
foreach ($result as $thread) {
print json_encode($thread['url']);
}
打印返回以下内容(有效的视频ID')
"UjN_aX84Qco""lB6K60mkmho""ReRcHdeUG9Y""aXD6prwrYGw""b6pvDKjp-_s"
到目前为止,一切都很顺利。这是jquery函数输出的html:
<div class="row">
<div class="large-3 small-6 columns">
<a class="th" id="small_th_1"><img src="http://placehold.it/500x500&text=LEL_Error"></a>
<div class="panel">
<p id="small_th_1_description">Description</p>
</div>
</div>
我想在这里添加一个基于php文件提供的视频ID的iframe,但是我无法使jquery功能起作用。这是jquery函数:
function getThreadsbyNumber() {
$.ajax({
type: "post",
url: "Ajax/getThreadsbyNumber.php",
dataType: "json",
success: function(data) {
$('#mainHeadline').html('<iframe width="320" height="240" src="//www.youtube.com/embed/'+data[0]+'?autoplay=1" frameborder="0""></iframe>');
$('#small_th_1').html('<iframe width="320" height="240" src="//www.youtube.com/embed/'+data[1]+'?autoplay=1" frameborder="0""></iframe>');
$('#small_th_2').html('<iframe width="320" height="240" src="//www.youtube.com/embed/'+data[2]+'?autoplay=1" frameborder="0""></iframe>');
$('#small_th_3').html('<iframe width="320" height="240" src="//www.youtube.com/embed/'+data[3]+'?autoplay=1" frameborder="0""></iframe>');
$('#small_th_4').html('<iframe width="320" height="240" src="//www.youtube.com/embed/'+data[4]+'?autoplay=1" frameborder="0""></iframe>');
}
});
}
答案 0 :(得分:1)
您不希望将JSON字符串拆分为多个位并逐块发送。 JSON的整个想法是它允许您将整个对象和/或数组编码为一个字符串。
而不是
$result = $mc->getThreadsbyNumber(5);
foreach ($result as $thread) {
print json_encode($thread['url']);
}
尝试将其作为一个字符串发送:
$result = $mc->getThreadsbyNumber(5);
print json_encode($result);
然后你可以这样访问它(在你的AJAX回调中):
success: function(data) {
//data.length - the number of $threads (which you were originally sending back one-by-one)
//data[0] - the first thread
//data[0][0] - the first field in the first thread
//for (var i = 0; i < data.length; i++) - loop through each thread
//for (var i = 0; i < data[0].length; i++) - loop through each field from thread 1
}
这些当然只是一些例子。了解如何构建JSON以找到最适合您的情况的方法。但无论如何,一个 AJAX请求应该提供一个响应。该响应可以是单个线程或多个数组,但它应该是一个 JSON编码的字符串。 另外,使用JSON validator确保您获得的JSON有效。
答案 1 :(得分:-1)
在你的ajax文件中:
$json = '[';
foreach ($result as $thread) {
$json += $thread['url'];
}
$json += ']';
echo $json;
你的返回字符串应该是:
["UjN_aX84Qco","lB6K60mkmho","ReRcHdeUG9Y","aXD6prwrYGw","b6pvDKjp-_s"]