在ajax的幫助下查詢產品后嘗試打開帶有產品詳細信息的模態時出現錯誤錯誤本身:Uncaught SyntaxError: Unexpected end of JSON inputat JSON.parse (<anonymous>)at HTMLButtonElement.<anonymous> (scripts.js:54)at HTMLDocument.dispatch (jquery-3.3.1.js:5183)at HTMLDocument.elemData.handle (jquery-3.3.1.js:4991)需要明確的是:我有一些過濾器,其結果在 pythonfilter_items函數中被過濾,然后它使用 JSONResponse 以字典(as_dict()項目模型中的函數)的形式將其發送到前端,并將它們添加到hidden input值中。JS 函數獲取隱藏的輸入值,并使用來自該輸入的數據呈現過濾結果。在過濾功能的幫助下查詢的項目模型:class Item(models.Model):ITEM_TYPES = ( ('UM', 'Umbrella'), ('SK', 'Skirt'), ('TR', 'Trousers'), ('OT', 'Other'))BRANDS = ( ('VS', 'Versace'), ('SP', 'Supreme'), ('SI', 'Stone Island'), ('FP', 'Fred Perry'),)title = models.CharField(max_length=256)image = models.ImageField(upload_to='img/')brand = models.CharField(max_length=256)type = models.CharField(choices=ITEM_TYPES, max_length=2)description = models.TextField(blank=True, null=True)season = models.TextField(blank=True, null=True)discount = models.FloatField(blank=True, null=True)price = models.FloatField()def __str__(self): return self.title + ' ' + self.typedef as_dict(self): data = {"title": self.title, "image": self.image.url, "brand": self.brand, "type": self.type, "discount": self.discount, "price": self.price, "rus_representation": self.rus_representation, "description": self.description, "season": self.season, "images": [self.image.url]} if self.images: for image in self.images.all(): data['images'].append(image.image.url) # data['dumped'] = json.dumps(data) # print(data['dumped']) return datadef dumped_as_dict(self): return json.dumps(self.as_dict())@propertydef rus_representation(self): if self.type == 'UM': return 'Зонтик' elif self.type == 'SK': return 'Юбка' elif self.type == 'TR': return 'Штаны' elif self.type == 'OT': return 'Другое'
1 回答

忽然笑
TA貢獻1806條經驗 獲得超5個贊
當您構建該 HTML 字符串時,您的代碼會執行以下操作:
var el = '<div ... value=' + JSON.stringify(x) + ' ... >';
因此,HTML 結果將是
var el = '<div ... value={ ... } ... >';
由于“value”的屬性值未在生成的 HTML 源中引用,因此 JSON 中的第一個空格字符是屬性值的結尾,就 HTML 解析器而言。
您至少需要包含引號:
var el = '<div ... value=\'' + JSON.stringify(x) + '\' ... >';
我還強烈建議您使用 HTML 實體編碼器對字符串中的任何 HTML 元字符進行編碼,例如
function scrubHtml(s) {
return s.replace(/[<>'"&]/g, function(meta) {
return "&#" + meta.charCodeAt(0) + ";";
});
}
添加回答
舉報
0/150
提交
取消