2017-04-18 118 views
2

我試圖建立一個Vue的模塊上我的網站shopify,所以我創建了一個集合JSON端點:shopify AJAX產品在收集

{% layout none %} 
{% paginate collection.products by settings.pagination_limit %} 
    { 
    "results": {{ collection.products | json }} 
    } 
{% endpaginate %} 

當我訪問該端點在/收集/集料穴?view = json我得到了所有產品的完整轉儲,但是當我得到的ajax是沒有嵌套產品的集合對象時。

我的ajax:

$.getJSON('/collections/mens-slip-on?view=json', function(response) { 
    console.log(response); 
    that.products = response; 
    }); 

我的結果:

Object {collection: Object} 

collection:Object 
description:(...) 
handle:(...) 
id:(...) 
image:(...) 
products_count:(...) 
published_at:(...) 
title:(...) 
updated_at:(...) 

我Vue的成分在全:

new Vue({ 
el: '#filterable', 
data: { 
collection: null, 
products: null 
}, 

mounted() { 
    this.initCollection(); 
    this.fetchProducts(); 
}, 

methods: { 

initCollection: function() { 
    var currPath = window.location.pathname; 
    this.collection = currPath.substring(currPath.lastIndexOf('/') + 1); 
}, 

fetchProducts: function() { 
    var that = this; 

    $.getJSON('/collections/mens-slip-on?view=json',  function(response) { 
    console.log(response); 
    that.products = response; 
    }); 
} 

} 

}); 

Vue.config.devtools = true; 

看來,不管我把我的collection.json .liquid模板它總是返回集合對象。

更新:我能夠通過使用XHR而不是jQuery來解決這個問題來完成ajax調用。看起來這個問題與jQuery getJSON有某種關係,但我不清楚其中的原因。

var httpRequest = new XMLHttpRequest(); 

    httpRequest.onreadystatechange = alertContents; 
    httpRequest.open('GET', '/collections/' + this.collection + '?view=json', true); 
    httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); 
    httpRequest.send(); 

    function alertContents() { 
    if (httpRequest.readyState === XMLHttpRequest.DONE) { 
     if (httpRequest.status === 200) { 
     var response = JSON.parse(httpRequest.responseText); 

     parent.products = response.results; 
     } 
    } 
    } 
+0

請問您可以添加更多vuejs相關代碼嗎? –

+0

Vue js代碼無關緊要,我只是調用一個運行ajax調用的方法。 –

+0

那有什麼相關的? :)當你向Postman中的那個api端點發出GET請求時(希望你使用它),你得到了什麼? –

回答

0

我相信你的電話是不正確的。

應該是更像

$.getJSON('/collections/mens-slip-on.json', function(response) { 
    console.log(response); 
    that.products = response; 
    }); 

這將JSON格式返回集合對象。如果你想要所有你需要的產品

$.getJSON('/collections/mens-slip-on/products.json', function(response) { 
    console.log(response); 
    that.products = response; 
    }); 
+0

不,這不是它的記錄方式,我使用模板開關變量'view = template_name' –