如何正确使用Jquery返回数组(ajax)



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>');
    }
    });
    }

您不希望将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验证器来确保您获得的JSON是有效的。

在您的ajax文件中:

$json = '[';
foreach ($result as $thread) {
    $json += $thread['url'];
}
$json += ']';
echo $json;

你的返回字符串应该像:

["UjN_aX84Qco","lB6K60mkmho","ReRcHdeUG9Y","aXD6prwrYGw","b6pvDKjp-_s"]

最新更新