【问题标题】:Photo album - jquery ajax json + php相册-jquery ajax json + php
【发布时间】:2012-02-11 19:13:10
【问题描述】:

我正在使用 ajax 制作相册。

js代码:

$(document).ready(function(){
  $('#next').click(function(){

    var next = $('#id').text();

    $.ajax({
        type: 'GET',
        url: 'URL', //This I changed for this post
        dataType: 'json',
        data: { "id" : next},
        success: function(data){
            alert(data.error);
            if(data.error == true)
            {
                alert(data.msg);
            }
            else
            {
            $('#pics').attr({
                src : data.src,
                witdth : data.width,
                height : data.height});
            $('#id').text(data.id);
            }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            alert(textStatus +' ' + errorThrown);
        }
    });
  });
});

php文件代码:

if(is_integer($_GET['id']))
{
$error = false;
$next = $_GET['id'] + 1;

switch($_GET['id'])
{
    case 1: $jsondata = '{"src" : "picture 01 valid path", ';
            $jsondata .= '"width" : xxx, ';
            $jsondata .= '"height" : xxx, ';
            $jsondata .= ' "id" : '.$next;
        break;
    case 2: $jsondata = '{"src" : "picture 02 valid path", ';
            $jsondata .= '"width" : xxx, ';
            $jsondata .= '"height" : xxx, ';
            $jsondata .= ' "id" : '.$next;
        break;
    ...+cases...
    default: $jsondata = '{"msg" : "An error occured. Please close the tab and enter again. Thanks."';
            $error = true;
}

$jsondata .= ', "error" : '.$error.'}';

echo json_encode($jsondata, true);
}

html代码: ‹img src="有效路径" width="xxx" height="xxx" /›

使用 chrome javascript 控制台时,错误是“错误”为空。我在网络上尝试了很多组合和可能性,但没有任何成功!你能帮我解决这个问题吗?

提前致谢!

P.S.:我仍然不确定此解决方案是否会在相册中导航:S 这是回答此问题后的另一个问题..

【问题讨论】:

  • 使用 Chrome 的检查器或 Firebug 检查响应。确保一个有效的对象正在返回并且data 存在。并将alert(data.error); 替换为console.log(data); 以查看它是否为有效对象。

标签: php jquery ajax


【解决方案1】:

您在 php 代码中创建了一个 json 字符串,因此您不必对其进行编码。

从您的 php 代码中删除这一行 echo json_encode($jsondata, true); 并仅删除 echo $jsondata 并尝试。

【讨论】:

    【解决方案2】:

    你不需要做json_encode,所以echo $jsondata就足够了

    【讨论】:

      猜你喜欢
      • 2011-02-19
      • 2010-11-18
      • 2012-05-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-05
      • 2012-10-13
      • 1970-01-01
      相关资源
      最近更新 更多