我尝试在shopify网站上构建Vue模块,因此我为集合创建了一个jSON端点:
{% layout none %}
{% paginate collection.products by settings.pagination_limit %}
{
"results": {{ collection.products | json }}
}
{% endpaginate %}
当我在/ collections / collection-slug访问该端点时?view = json我得到了所有产品的完整转储但是当我得到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 :(得分: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;
});