首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >ajax json.stringify请求从字符串转换为元素php

ajax json.stringify请求从字符串转换为元素php
EN

Stack Overflow用户
提问于 2014-04-06 21:12:37
回答 1查看 811关注 0票数 0

我遇到了这个问题,我的Ajax JSON.stringify的一部分以文本的形式到达,另一部分类似于数组元素,我的问题是如何将所有内容转换为数组并提取元素值,下面是我在我的PHP脚本中接收到的代码:

代码语言:javascript
运行
复制
    array (size=3)
    'JSON' => string '  {
    "requestType":"TourListRequest",
    "data":{
    "ApiKey":"12345",
    "ResellerId":"1000",
    "SupplierId":"1004",
    "ExternalReference":"10051374722994001",
    "Timestamp":"2013-12-10T13:30:54.616+10:00",
    "Extension":{
     "any":{
    }
   },
    "Parameter":{
    "Name":{
      "0":" "
     },
    "Value":{
    }
    }
   }
  }
   ' (length=412)
   'URL' => string 'api_test_json.php?test=JSON Tour List' (length=37)
   'Type' => string 'JSON Tour List' (length=14)

我的问题是:如何获得"requestType“、"ApiKey”、"ResellerId“等作为PHP变量的值?

这是我生成AJAX调用的代码:

代码语言:javascript
运行
复制
<textarea style="width: 100%; height: 300px;" id="request_json">
{
    "requestType":"TourListRequest",
    "data":{
    "ApiKey":"12345",
    "ResellerId":"900",
    "SupplierId":"904",
    "ExternalReference":"10051374722994001",
    "Timestamp":"2013-12-10T13:30:54.616+10:00",
    "Extension":{
     "any":{
      }
     },
     "Parameter":{
     "Name":{
     "0":" "
      },
      "Value":{

      }
     }
    }
   }

代码语言:javascript
运行
复制
 <script>
 function SubmitAPI(){
var sendInfo = { JSON: $('#request_json').val(),
    URL: $('#supplier_api_endpoint_JSON_Tour_List').val(),
Type: 'JSON Tour List' };
       $('#response_json').html("Calling API...");
   $.ajax({
    url: "post_JSON.php",
        data: {data: JSON.stringify(sendInfo)},
    dataType: 'html',   
    type: "POST",
    cache: false,
    success: function(data){
      console.log(data)
      $('#response_json').html(data);
      }
    });
      }
     </script>

谢谢你提前..。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-04-06 21:22:12

您只需解码JSON并访问结果对象数据中的变量。

代码语言:javascript
运行
复制
$array = ...; // the array you dump in your example
$obj = json_decode($array['JSON']);
// request type information
$request_type = $obj->requestType;
// here is all the stuff in 'data'
$data = $obj->data;
// now access your data variables like
echo $data->ApiKey;
echo $data->ResellerId;
// and so on...

这里大部分工作都是由json_decode()步骤完成的。JSON只是对象和/或数组数据的序列化方法。一旦您通过json_decode()反序列化它,您就可以直接访问任何被序列化成JSON的数据结构,就像任何普通的数字索引数组或stdClass对象(PHP的默认对象类型)一样。

注意,在使用此函数时,经常会看到true作为第二个参数传递。这将JSON对象结构转换为关联数组,而不是stdClass对象。我个人很少使用这种方法,因为在很多情况下,对象结构{}中的项应该更多地作为PHP中的对象来处理,而不是更像映射的关联数组。然而,由于某些原因,在PHP中工作的人更倾向于使用关联数组,因此您将在很多例子中看到这一点(比如json_decode($json, true))。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22900117

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档