【问题标题】:Accessing the properties of objects after an AJAX call在 AJAX 调用之后访问对象的属性
【发布时间】:2012-10-01 09:30:23
【问题描述】:

我进行了一个 ajax 调用,并以这种形式从控制器中取回数据。

Array
(
[0] => stdClass Object
    (
        [cat_id] => 2
        [title] => Clothes
        [description] => Clothing for men and women
        [active_coupon_counter] => 0
        [store_id] => 1
    )

[1] => stdClass Object
    (
        [cat_id] => 17
        [title] => Designer
        [description] => ;description
        [active_coupon_counter] => 0
        [store_id] => 1
    )

[2] => stdClass Object
    (
        [cat_id] => 24
        [title] => Fashion
        [description] => ;description
        [active_coupon_counter] => 0
        [store_id] => 1
    )

)
Array

这可能看起来很愚蠢,但我不知道如何访问每个数组中的 cat_idtitle 属性!

有什么帮助吗,伙计们?

谢谢。

【问题讨论】:

    标签: javascript ajax


    【解决方案1】:

    您似乎正在获取数据的 PHP var_dump 或 print_r。这不是很方便解析的东西。

    我不知道任何用于该格式的 JavaScript 解析器,因此您可能必须从头开始编写一个。问题Tutorials for writing a parser with Javascript 应该为您提供有关该主题的指导。

    您最好编辑服务器端脚本,以更合理的格式(例如 JSON 或 XML)返回数据。

    【讨论】:

      【解决方案2】:

      您可以只使用对象表示法来访问它们:

      array[0].cat_id
      // returns 2
      

      更新

      从你的服务器返回的格式必须是JSON,它应该是这样的:

      [
          {
              "cat_id": 2,
              "title": "Clothes",
              "description": "Clothing for men and women",
              "active_coupon_counter": 0,
              "store_id": 1
          },
          {
              "cat_id": 17,
              "title": "Designer",
              "description": ";description",
              "active_coupon_counter": 0,
              "store_id": 1
          },
          {
              "cat_id": 24,
              "title": "Fashion",
              "description": ";description",
              "active_coupon_counter": 0,
              "store_id": 1
          }
      ]
      

      【讨论】:

      • 你能告诉我们你的实际程序吗?您返回的数据看起来如何
      • 这就是它的样子。我做了一个“警报”,这出现了。
      • 那么这就是字符串包含的内容,javascript 将无法理解该格式,您必须将其更改为有效的 JSON
      • 请解释投反对票,当有人无缘无故投反对票时真的很烦人。
      • 还有!我做了 json_encode 并且我正在以 JSON 格式取回数据。谢谢。 :)
      【解决方案3】:

      您似乎正在使用 JSON 来发送和接收数据。

      所以你可以访问数组对象并使用:

      yourArrayObject[indexYouWantToAccess].cat_id
      

      【讨论】:

      • "您好像在使用 JSON 来发送和接收数据。" — 问题中的数据看起来不像 JSON!
      • 你能把代码放在你从控制器接收数据的地方吗?
      【解决方案4】:

      您是否使用mysql_fetch_object 从数据库中获取数据?尝试使用mysql_fetch_assocmysql_fetch_array

      此外,响应似乎不是有效的 json 响应,因为 json_encodemysql_fetch_objectmysql_fetch_assoc/array 上都能正常工作。

      【讨论】:

        猜你喜欢
        • 2017-05-08
        • 2013-09-08
        • 2011-03-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多