【问题标题】:Post Json array in url在 url 中发布 Json 数组
【发布时间】:2018-11-10 10:23:56
【问题描述】:

是否可以在 URL 中传递 JSON?

例如,我有一个数组:

data = {  
  "name": "test",
  "user_id": 1
}

我想将它传递给一个 URL,例如:

http://example.com/jsonArray

【问题讨论】:

  • data 在你的情况下不是一个数组,它是一个 JSON 对象。为什么不使用 POST 方法发送数据对象?
  • 是的,你可以,但你到底为什么想要这个?这就是 POST 请求的用途:)
  • 不能使用 post 方法,因为必须创建一个特定的 url 来调用 api。
  • 也许看看 graphql api,它似乎比休息更适合你想做的事情
  • 处理发布请求及其工作,但我们的任务是创建一个特定的 url 来调用 api。

标签: php json url


【解决方案1】:

你最好使用 POST 来传递这种类型的数据,但是,你绝对可以做一个:

$str = serialize(json_decode($data, true));

然后在 url 中传递给你 $str。

【讨论】:

    【解决方案2】:

    您无法直接发送 JSON 数组,但您可以通过一种允许将其发送到您的 API 的方式对其进行准备。您将 JSON 转换为字符串并对其进行编码,以便将其正确格式化为 GET。

    // your JSON data
    var data = '{"name":"Homer Simpson","status":"Suspended","disciplinary-dates":["2018-01-2","2018-02-14","2018-03-17"]}' ;
    
    // take your JSON, turn it into a string and then encode it 
    var urlParams = encodeURIComponent(JSON.stringify(data)) ;
    
    // your URL adding your JSON data as the value
    var url = 'http://example.com/?params=' + urlParams ;
    

    在 PHP 端你将解码

      // note: this code does not have any error checking - you should add it      
      // get your params
      $params = $_GET['params'] ;
    
      // decode the string
      $decodedParams = urldecode($params) ;
    
      // turn your string into an array
      $wasJSONAsArray = json_decode($decodedParams, true) ;
    
      // turn your string into a std object
      $wasJSONAsStdObj = json_decode($decodedParams) ;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-11
      • 2017-08-26
      • 1970-01-01
      相关资源
      最近更新 更多