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 vscode问题请教
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM