2016-03-15 120 views
0

我想使用一个jQuery插件倒计时。 (我也使用PHP框架)。这是我的主网页脚本:jquery getjson函数:回调返回错误的字符串

<script type="text/javascript"> 
$(document).ready(function() { 
    $.get(baseUrl + "/countdown", {id: "609|610|611|612"}, function (data) { 
     auctions = data.split("||"); 
     for (n = 0; n < auctions.length; n++) { 
      if (auctions[n] != undefined) { 
       divis = auctions[n].split("##"); 
       if (divis[1] != "stop") { 
        $('#bid' + divis[0]).countdown(divis[1], function (event) { 
         var totalHours = event.offset.totalDays * 24 + event.offset.hours; 
         $(this).html(event.strftime(totalHours + ' hr %M min %S sec')); 
        }); 

       } else { 
        $('#bid' + divis[0]).html("closed"); 
       } 

      } 
     } 
    }); 
}); 

的“倒计时”是一个PHP文件,返回字符串:

609##stop||610##stop||611##2016/03/28 13:00:56||612##2016/04/03 01:00:00|| 

用这个,使我太多错误。如果我将“auctions.length”更改为“4”,所有内容都会变得正确和正确!我检查了“数据”的值,而不是“countdown.php”返回的确切字符串,它更大并包含一些空格!我也检查了“auctions.length”的值,它是7! 我不知道为什么会发生这种情况。

也当我更改$ .get到$ .getJSON没有倒计时显示。这是为什么?

感谢您的关注:) 并感谢您对我的英语错误的宽容。

回答

0

因为您的响应数据不是JSON格式,所以$ .getJSON什么也没有,我建议您使用JSON格式进行响应。

在PHP

$data = array(
    array(
     'id' => '609', 
     'datetime' => 'stop' 
    ), 
    array(
     'id' => '610', 
     'datetime' => 'stop' 
    ), 
    array(
     'id' => '611', 
     'datetime' => '2016/03/28 13:00:56' 
    ), 
    array(
     'id' => '612', 
     'datetime' => '2016/04/03 01:00:00' 
    ) 
); 
echo(json_encode($data)); 

,并在JavaScript

$(document).ready(function() { 
    $.getJSON(baseUrl + "/countdown", {id: "609|610|611|612"}, function (auctions) { 
     for (n = 0; n < auctions.length; n++) { 
      if (auctions[n] != undefined) { 
       divis = auctions[n]; 
       if (divis.datetime != "stop") { 
        $('#bid' + divis.id).countdown(divis.datetime, function (event) { 
         var totalHours = event.offset.totalDays * 24 + event.offset.hours; 
         $(this).html(event.strftime(totalHours + ' hr %M min %S sec')); 
        }); 

       } else { 
        $('#bid' + divis.id).html("closed"); 
       } 

      } 
     } 
    }); 
}); 
+0

不要忘记设置Content-Type的响应头,当你输出HTML以外的东西。 PHP默认声称所有输出都是HTML。 – Quentin

+0

@学习:谢谢,但它没有work.still与getJSON我没有倒计时。有趣的是当我添加console.log(数据); - 当我使用get() - 这是什么控制台显示我:609 ## stop || 610 ## stop || 611 ## 2016/03/15 20:20:56 || 612 ## 2016/04/03 01:00:00 || <!doctype html> .....<! - Body Close - >它将整个html附加到“data”! – Niloofar