【问题标题】:How to read JSON output with the object named "@attributes"? [duplicate]如何使用名为“@attributes”的对象读取 JSON 输出? [复制]
【发布时间】:2019-10-16 15:01:09
【问题描述】:

使用 JQuery AJAX,我将 HTTP 请求发送到 PHP 后端,并尝试使用 json_encode() 函数将解析为 JSON 的 XML 字符串检索回前端。一些 XML 包含属性,在输出中显示 @attributes。不知何故,我尝试console.log() @attributes 但失败了。详情如下:

  1. 在前端,我使用 JQuery AJAX 向我的一个 PHP 文件发送 HTTP 请求。

  2. 在后端 PHP 中,我从 DB 中检索数据,其中一列包含 XML 字符串。

  3. 然后,检索后,我使用simplexml_load_string()函数将XML的String转换为真正的XML。

  4. 这里是XML字符串的例子:

<dsconnector>
    <statement>
        SELECT SUM(a.doc_amt) FROM gl_temp_trx_dt as a INNER JOIN gl_temp_trx_hd as b ON a.gl_hd_unique_id = b.unique_id
    </statement>
    <filter id="company123" range="false">
        <label>Company</label>
        <table>company</table>
        <field>company_code</field>
        <alias>a</alias>
        <desc>company_name</desc>
        <dependee>glacc, glyear, glperiod</dependee>
    </filter>
</dsconnector>

注意&lt;filter&gt; 有两个属性

  1. 之后我使用json_encode()函数输出转换后的XML

  2. 在前端,我使用console.log()函数查看输出的样子,下面是部分结果:

0: {…}
  "@attributes": {…}
     id: "companyFilterId"
     range: "false"
     <prototype>: Object { … }
  alias: "ar"
  dependee: "projectFilterId_0123, phaseFilterId_ABCD, debtorAccFilterId"
  desc: "company_name"
  field: "company_code"
  label: "Company"
  table: "company"
  <prototype>: Object { … }
...
  1. 如您所见,属性部分包含“@”。并使用此代码打印结果:
...[other AJAX part]...
success: function(data, textStatus, XMLHttpRequest)
         {
               if (data.status==1)
               {
                  console.log(data.result[0].attributes);
               }
                  else if(data.status==0)
               {

               }
         },
...[other AJAX part]...

它会说attributes 是未定义的。


我的问题是,如何显示名为“@”的对象的 JSON 数组。就像在这种情况下,它显示“@attributes”。提前致谢。

【问题讨论】:

    标签: javascript php jquery json ajax


    【解决方案1】:

    API 这样做很令人沮丧。您应该可以像这样访问它:

    data.result[0]['@attributes']
    

    【讨论】:

    • 好的,这很简单。当我在互联网上寻找解决方案但找不到任何解决方案时,我花了很长时间才弄清楚这一点。非常感谢@ceejayoz。等待时间后我会接受这个答案。
    猜你喜欢
    • 2021-07-04
    • 2018-05-29
    • 2017-12-05
    • 2021-09-03
    • 2019-01-20
    • 2016-08-19
    • 2020-06-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多