dongquelu1239 2012-11-24 09:27
浏览 46
已采纳

Jquery getJSON php数组到javascript

I am testing the getJSON with php array, but it is not working, can anyone check for me ? I feel the problem is from the php code because when i test the html code with getJSON url https://graph.facebook.com/zombies, it is working.

In my array.php

<?php

 header("Content-type: text/javascript");

 $arr = array(

            "name" => "Tim",
            "age" => "28"     );

echo json_encode($arr);

?>

In my test.html :

  <html>
  <head>
    <script type='text/javascript' src='jquery.js'></script>
  </head>
  <body>

    <script type='text/javascript'>

    $(document).ready(function() {
         $.getJSON('array.php', function(data) {        
            if(data) {
            document.write(data.age);       
            }
            else {
            alert('error');
            }
        });
    }); 
    </script>

   </body>
   </html>
  • 写回答

3条回答 默认 最新

  • dongshilve4392 2012-11-24 09:32
    关注

    header("Content-type: text/javascript");

    You're telling the browser you're sending it JavaScript, when what you're sending it is JSON. The content type for JSON is application/json.

    If you fix that, it should work, provided you're not running afoul of the Same Origin Policy. If you're making a cross-domain request, your options are:

    • Don't use ajax and JSON, use JSON-P.

    • Use CORS, but it requires that the server allow your document's origin, and that the browser supports it (most modern ones do, older ones don't).

    • Use YQL as a cross-domain proxy.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器