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 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?