Jquery getJSON php 数组到 javascript

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13539964/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 19:05:55  来源:igfitidea点击:

Jquery getJSON php array to javascript

phpjavascriptjquerygetjson

提问by jc_tan

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.

我正在用 php 数组测试 getJSON,但它不起作用,谁能帮我查一下?我觉得问题来自 php 代码,因为当我使用 getJSON url https://graph.facebook.com/zombies测试 html 代码时,它正在工作。

In my array.php

在我的array.php

<?php

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

 $arr = array(

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

echo json_encode($arr);

?>

In my test.html :

在我的 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>

回答by GBD

Change

改变

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

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

To

header('Content-Type: application/json');

For JSONP

对于 JSONP

header('Content-Type: application/javascript');

回答by T.J. Crowder

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

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.

您告诉浏览器您发送的是 JavaScript,而您发送的是 JSON。JSON 的内容类型是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:

如果你解决了这个问题,它应该可以工作,前提是你没有违反Same Origin Policy。如果您要进行跨域请求,您的选择是:

  • 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.

  • 不要使用 ajax 和 JSON,使用JSON-P

  • 使用CORS,但它要求服务器允许您的文档来源,并且浏览器支持它(大多数现代的支持,旧的不支持)。

  • 使用YQL 作为跨域代理

回答by rekire

Try to set the content type to

尝试将内容类型设置为

application/json

So jQuery will interpte as json data

所以 jQuery 会插入为 json 数据