在ajax的幫助下查詢產(chǎn)品后嘗試打開帶有產(chǎn)品詳細(xì)信息的模態(tài)時出現(xiàn)錯誤錯誤本身: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)需要明確的是:我有一些過濾器,其結(jié)果在 pythonfilter_items函數(shù)中被過濾,然后它使用 JSONResponse 以字典(as_dict()項(xiàng)目模型中的函數(shù))的形式將其發(fā)送到前端,并將它們添加到hidden input值中。JS 函數(shù)獲取隱藏的輸入值,并使用來自該輸入的數(shù)據(jù)呈現(xiàn)過濾結(jié)果。在過濾功能的幫助下查詢的項(xiàng)目模型: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貢獻(xiàn)1806條經(jīng)驗(yàn) 獲得超5個贊
當(dāng)您構(gòu)建該 HTML 字符串時,您的代碼會執(zhí)行以下操作:
var el = '<div ... value=' + JSON.stringify(x) + ' ... >';
因此,HTML 結(jié)果將是
var el = '<div ... value={ ... } ... >';
由于“value”的屬性值未在生成的 HTML 源中引用,因此 JSON 中的第一個空格字符是屬性值的結(jié)尾,就 HTML 解析器而言。
您至少需要包含引號:
var el = '<div ... value=\'' + JSON.stringify(x) + '\' ... >';
我還強(qiáng)烈建議您使用 HTML 實(shí)體編碼器對字符串中的任何 HTML 元字符進(jìn)行編碼,例如
function scrubHtml(s) {
return s.replace(/[<>'"&]/g, function(meta) {
return "&#" + meta.charCodeAt(0) + ";";
});
}
添加回答
舉報
0/150
提交
取消