dongya2578 2014-07-24 17:05
浏览 24
已采纳

AJAX请求接受硬编码的JSON,但不接受软编码

This AJAX request returns 'success' if the output in PHP is copied and pasted JSON, but 'fail' if it's generated by the file. Have a look at the comments in api.php below to see what I mean.

$.ajax({
    url: 'api.php',
    dataType: 'JSON',
    success: function() {
        alert('success');
    },
    error: function() {
        alert('fail');
    }
});

api.php:

<?php
header('Access-Control-Allow-Origin: *');

$jsonurl = "http://findyourmp.parliament.uk/api/search?q=st+pancras&f=js";
$json = file_get_contents($jsonurl);

// THIS DOESN'T WORK (RETURNS 'FAIL')
print_r($json);
?>

<!-- THIS WORKS (RETURNS 'SUCCESS') -->
{"results": { "constituencies": [{"constituency_name": "Holborn and St Pancras", "member_name": "Frank Dobson", "member_party": "Labour", "member_biography_url": "http://www.parliament.uk/biographies/commons/Frank-Dobson/180", "member_website": "", "uri": "http://findyourmp.parliament.uk/constituencies/holborn-and-st-pancras.json" } ], "members": [] }}
  • 写回答

1条回答 默认 最新

  • dongqian1028 2014-07-24 17:07
    关注

    I think you want

    echo $json;
    

    not

    print_r($json);
    

    $json is a string, so you just want to print it, which is what echo does.

    print_r on the other hand:

    Prints human-readable information about a variable

    The moral of the story: Look at the output of your PHP script. Test pieces and verify that each piece is working, instead of trying to test the entire system.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler