首页 > 解决方案 > 如何在 jquery 中获取 json 键和值?

问题描述

我正在使用 jquery ajax 获得 Woocommerce 订单的 json 格式结果。

j.ajax({

  type: 'GET',
  url: 'https://www.mywebsite.com/wp-json/wc/v2/orders/123456',
  cache: false,
  data: {
    format: 'json'
  },
  headers: {
      "Authorization": "Basic " + btoa("my_key" + ":" + "my_secret")
  },
  success: function(data) {
    var result = JSON.parse(data);
    //console.log(data);
    console.log(result);
    console.log(result[id]);

  },
  error: function(xhr,status,error) {
    console.log(error);
  },
  complete: function() {
  }

});

我在控制台中收到上面的错误消息:

jqueryscript.js?ver=4.9.7:173 Uncaught ReferenceError: id is not defined at Object.success (jqueryscript.js?ver=4.9.7:173) at i (jquery.js?ver=1.12.4:2)

这是json的样子:

{
  "id": 0003,
  "parent_id": 0,
  "number": "0003",
  "order_key": "wc_order_dsadsa003",
  "created_via": "checkout",
  "version": "3.3.1",
  "status": "processing",
  "currency": "dollar",
  "date_created": "2018-06-27T02:52:40",
  "date_created_gmt": "2018-06-27T02:52:40",
  "date_modified": "2018-06-27T02:52:41",
  "date_modified_gmt": "2018-06-27T02:52:41",
  "discount_total": "0.00",
  "discount_tax": "0.00",
  "shipping_total": "0.00",
  "shipping_tax": "0.00",
  "cart_tax": "0.00",
  "total": "448.00",
  "total_tax": "0.00",
  "prices_include_tax": false,
  "customer_id": 1,
  "customer_ip_address": "127.0.0.1",
  "customer_user_agent": "mozilla/5.0 (windows nt 10.0; win64; x64) applewebkit/537.36 (khtml, like gecko) chrome/67.0.3396.99 safari/537.36",
  "customer_note": "",
  "billing": {
    "first_name": "",
    "last_name": "",
    "company": "",
    "address_1": "adasd",
    "address_2": "",
    "city": "asdas",
    "state": "",
    "postcode": "8000",
    "country": "",
    "email": "johndoe@gmail.com",
    "phone": "1213123"
  },

您知道如何获取值为0003和值为adasd的address_1的字段id吗?

我想把它放到一个 html 元素中。任何想法都值得赞赏。谢谢

标签: javascriptphpjqueryhtmlwordpress

解决方案


不要

控制台.log(结果[id]);

控制台.log(result.id);


推荐阅读