2012-04-04 68 views
1

PHP5.1.6没有json_encode(),所以我想使用json_encode documentation上的函数。 我想使用这个功能的输出与Ajax请求:json_encode使用PHP 5.1.6和jQuery

fetchArticles: function(e) { 
     $.ajax({ 
     url: 'article.php', 
     type: 'POST', 
     data: { id: $(this).data('id_prod') }, 
     dataType: 'json', 
     success: function(results) { 
      console.log('finished'); 
      console.log(results); 
     } 
     }); 

article.php我在这个时候:

if (isset($_POST['id'])) { 
connect(); 
$articles = get_articles($_POST['id']); 
echo json_encode($articles); return; 
} 

问题是与返回结果到JS控制台:

  • 如果没有结果,则打印空数组,
  • 如果有一个结果,则打印适当的对象,
  • 但是当有多个结果时,没有任何内容正在打印到控制台,甚至没有字finished

我可以在HTTP标头和响应中看到正确的数据被返回,但它不会被打印到控制台。你能帮我解决这个问题吗?

+1

您可以提供您要发送的示例JSON吗? – 2012-04-04 13:51:27

+0

以下是HTTP响应的结果:'[{“id_news”:“38”,“img”:“1313153502.jpg”,“no”:“2”,“title”:“Lorem ipsum”}, {“id_news”:“39”,“img”:“1313153981.jpg”,“no”:“2”,“title”:“Ipsum lorem”}]' – user1292810 2012-04-04 13:56:07

+0

Ooops,我不够精确。在标题中我有字符''',它会导致'SyntaxError:JSON.parse:坏转义字符'。我怎样才能避免这种情况? – user1292810 2012-04-04 20:37:48

回答

1

当JSON文件不能转换它抛出parsererror例外,所以试试这个:

$.ajax({ 
    url: 'article.php', 
    type: 'POST', 
    data: { id: $(this).data('id_prod') }, 
    dataType: 'json', 
    success: function(results) { 
     console.log('finished'); 
     console.log(results); 
    }, 
    error: function(jqXHR, textStatus, errorThrown) { 
     console.debug(jqXHR, textStatus, errorThrown); 
    } 
    }); 

它将输出你的错误时,JSON是无效的。

+0

感谢您的回答。我得到了如下输出:'SyntaxError:JSON.parse:bad escapeped character',我检查它是由''字符引起的。如果我从数据中删除它,一切正常。我怎样才能避免这种情况? – user1292810 2012-04-04 20:39:54

+0

你可以在它之前使用'\'来逃避你的'''。替换你的数据,现在我不记得做过它的PHP函数了,但是json_encode是为你设计的......但是......祝你好运:) – 2012-04-04 20:51:38

+0

我用'''替换了所有的引用字符'谢谢! – user1292810 2012-04-05 06:16:48