【问题标题】:Cannot read property apiRest无法读取属性 api Rest
【发布时间】:2017-08-21 23:03:54
【问题描述】:

我对这个 api 有疑问。

这是在html中

<div id="summary"></div>

这是在 JS 中

var consuKey = "ck_b04aa6f288ee9a5495dee9c5db0a6b136350e005";
var consuSecr = "cs_1f98d389d0f9b47cd3200023864cf9b7cba50574";

function callurl() {
$.ajax({
   url: 'https://test.juand.org/wc-api/v2/reports/sales?',
   data:{
        filter: {period: "last_week"},
        consumer_key: consuKey,
        consumer_secret: consuSecr
    },
type: "GET",
dataType: "json"
})
.done(function(data){
JsonpCallback(data.reports)
})
.fail(function(data){
console.log("no");
})
}

function JsonpCallback(json) {
for (var i = 0; i < json.length; i++) {
$('#summary').append('<b>Descripción:</b> ' + json[i].total_sales + '<br />');
$('#summary').append('<hr />');
}
}

callurl();

我有以下错误

Uncaught TypeError: Cannot read property 'length' of undefined
    at JsonpCallback (VM2284:68)
    at Object.<anonymous> (VM2284:60)
    at fire (VM2283 jquery-2.2.4.js:3187)
    at Object.fireWith [as resolveWith] (VM2283 jquery-2.2.4.js:3317)
    at done (VM2283 jquery-2.2.4.js:8757)
    at XMLHttpRequest.<anonymous> (VM2283 jquery-2.2.4.js:9123)

这个想法是 json (total_sales) 的结果,但如果我使用 JsonpCallback (data.reports),我仍然不明白为什么它会给我错误

JsonpCallback (data.sales)

不给出任何结果

你能帮我找到解决办法吗,谢谢!!

你可以在这里看到我的代码

Https://jsfiddle.net/JDLA1/a84v2x9w/2/

【问题讨论】:

    标签: javascript jquery json ajax woocommerce


    【解决方案1】:

    您拥有的 JSON 不是数组,因此没有 .length。 您可以删除循环

    function JsonpCallback(json) {
      $('#summary').append('<b>Descripción:</b> ' + json.total_sales + '<br />');
      $('#summary').append('<hr />');
    }
    

    此外,它是sales,而不是报告

    .done(function(data){
        JsonpCallback(data.sales)
    })
    

    另一方面,json.totals 是一个数组,所以如果你想迭代它,你可以这样做:

    for (var key in json.totals) {
        console.log("key:", key, "value:", json.totals[key])
    }
    

    【讨论】:

      猜你喜欢
      • 2019-11-26
      • 1970-01-01
      • 2014-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-29
      • 2020-11-06
      • 2011-01-07
      相关资源
      最近更新 更多