dqroc48068 2013-02-05 16:06
浏览 28
已采纳

苦苦挣扎的小json和php获取IP

PHP

<?php
header('Content-type: application/json');
$return['ip'] = $_SERVER['REMOTE_ADDR'];  
$results[] = array(
      'ip' => $return['ip']
   );
echo json_encode($results);
?>

jQuery

$.getJSON("http://domain.com/json/",
        function(data){
            console.log(data.ip);
        });
    });

But when I run the jQuery I've checked Fire bug and it says the following

GET http://domain.com/json/ 200 OK 81ms

And doesn't respond with the IP that I requested for. Have I missed something?

UPDATED CODE

PHP

<?php
header('Content-type: application/json');
$return['ip'] = $_SERVER['REMOTE_ADDR'];  
$results = array(
      'ip' => $return['ip']
   );
echo json_encode($results);
?>

jQuery

$.getJSON("http://domain.com/json/", function(data){
            console.log(data.ip);
        });

Firebug Error

SyntaxError: invalid label {"ip":"XXX.XXX.XXX.X"}

An arrow points at the first quotation mark just before the word ip.

  • 写回答

1条回答 默认 最新

  • douzhe9927 2013-02-05 16:13
    关注

    You are returning:

    [{'ip': 'XXX.XXX.XXX.XXX'}]
    

    But you are treating it as if you are returning:

    {'ip': 'XXX.XXX.XXX.XXX'}
    

    You either need to change your JavaScript to console.log(data[0].ip) or change your PHP to: $results = array( ... ); rather than $results[] = array( ... );

    Either will fix your problem. :)

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

报告相同问题?

悬赏问题

  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)