• 请不要在回答技术问题时复制粘贴 AI 生成的内容
Famio
V2EX  ›  程序员

请教,这种数据接口怎么写?

  •  
  •   Famio · Sep 18, 2017 · 4676 views
    This topic created in 3335 days ago, the information mentioned may be changed or developed.

    给的 demo 是:xxx.com/api/?id=123,抛出 json 数据格式。

    我只会写:xxx.com/api/index.php?id=123,用的 POST 方法,不会抛出 json 数据格式。

    有没有大神教我一下,随便给个例子就行,我一看就懂。

    Supplement 1  ·  Sep 18, 2017
    谢谢各位,发现光 echo 出来没用,还要加 header('content-type:application/json');改变下头
    20 replies  •  2017-09-18 22:24:57 +08:00
    inmyfree
    inmyfree
    Sep 18, 2017
    1
    你需要学习下.htaccess 规则
    icedx
    icedx
    Sep 18, 2017
    2
    你需要学习下nginx.conf 的写法
    Famio
    Famio
    OP
    Sep 18, 2017
    3
    @inmyfree @icedx 我知道你们的意思,但是我不是要 rewrite。重点在于如何抛出 json,我不会这块。
    sculley
    sculley
    Sep 18, 2017
    4
    demo 的 url 要有路由才行,要不是 nginx 配置,要不就是 index.php 入口后自己写路由判定,然后 call function
    U7Q5tLAex2FI0o0g
    U7Q5tLAex2FI0o0g
    Sep 18, 2017
    5
    如何抛出 json ?最简单暴力的:

    $arr = [
    'a' => 'aaa',
    'b' => 'bbb'
    ];
    echo json_encode($arr);
    exit(0);

    当然这么写一点都不优雅
    inmyfree
    inmyfree
    Sep 18, 2017
    6
    @Famio #3

    抛出 json ?

    php 直接 echo 啊,想要啥 格式就啥格式啊
    sculley
    sculley
    Sep 18, 2017
    7
    再加个 header ContentType
    pathletboy
    pathletboy
    Sep 18, 2017❤️5
    8
    不小心点开了楼主的示例网站,然后就。。。
    inmyfree
    inmyfree
    Sep 18, 2017
    9
    你要理解,http 返回的其实都是文本,里面内容你自己写就可以,要 html 就输入 <html>....要 json 就直接 echo,一样的
    inmyfree
    inmyfree
    Sep 18, 2017
    10
    @pathletboy #8 额...这就尴尬了,不说我还不知道,xxx.com 。。。默哀,前后左右还有妹子吗
    chuhemiao
    chuhemiao
    Sep 18, 2017
    11
    json_encode 解决不了问题?
    Immortal
    Immortal
    Sep 18, 2017
    12
    我草...在公司不小心点开了
    zjp
    zjp
    Sep 18, 2017 via Android
    13
    惨案,不只一两次了…示例网站用 example.com 不要用 xxx.com🌚
    KomeijiSatori
    KomeijiSatori
    Sep 18, 2017
    14
    ![photo_2017-09-18_14-09-24.jpg]( https://i.loli.net/2017/09/18/59bf635007b90.jpg)
    kltt22
    kltt22
    Sep 18, 2017
    15
    index.php 是默认页面啊,可以忽略。echo 不加头也可以返回正确 json,我一直是这样做的。
    scofieldpeng
    scofieldpeng
    Sep 18, 2017
    16
    php 抛出 json 不是就是 json_encode?然后 header 加上 application/json 就行了?遇到问题第一先 google
    paw
    paw
    Sep 18, 2017
    17
    靠。。。。。。好奇心杀死猫
    scofieldpeng
    scofieldpeng
    Sep 18, 2017
    18
    @kltt22 有时候客户端比如浏览器,如果不加有些前端框架不会认为是 json,因此严格来讲,最好加上 json 的 header 头
    yanzixuan
    yanzixuan
    Sep 18, 2017
    19
    @inmyfree 不一定,之前跟 java 的哥们联调我的接口的时候,直接报错。如果 header 没有指定 json 的话,java 的对应库会比较严格,不认为是个 json...
    wizardoz
    wizardoz
    Sep 18, 2017
    20
    提问请讲清楚问题描述,比如以多大的初速度和多大角度抛出 json ?
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   1319 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 42ms · UTC 19:20 · PVG 03:20 · LAX 11:20 · JFK 14:20
    ♥ Do have faith in what you're doing.