【问题标题】:Uncaught SyntaxError: Unexpected end of JSON input. Can't properly parse the info to JSON from the html未捕获的 SyntaxError:JSON 输入意外结束。无法将信息从 html 正确解析为 JSON
【发布时间】:2018-12-29 15:47:44
【问题描述】:

在使用 ajax 查询产品后尝试打开带有产品详细信息的模式时出现错误

错误本身:

Uncaught SyntaxError: Unexpected end of JSON input
at 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)

要明确:我有一些过滤器,其结果在 python filter_items 函数中过滤,然后它使用 JSONResponse 将其发送到前端 以字典的形式(Item 模型中的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.type

def 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 data

def dumped_as_dict(self):
    return json.dumps(self.as_dict())

@property
def rus_representation(self):

    if self.type == 'UM':
        return 'Зонтик'
    elif self.type == 'SK':
        return 'Юбка'
    elif self.type == 'TR':
        return 'Штаны'
    elif self.type == 'OT':
        return 'Другое'

内部带有过滤功能的基于类的视图:

class ProductsListView(ListView):
model = Item
types = Item.ITEM_TYPES
brands = Item.BRANDS

def get_context_data(self, **kwargs):
    context = super().get_context_data(**kwargs)
    context['types'] = self.types
    context['brands'] = self.brands
    return context

@classmethod
def filter_items(cls, request, *args, **kwargs):
    if request.is_ajax():
        data = request.GET

        queryset = Item.objects.all()

        if not data['type'] == 'ALL':
            queryset = queryset.filter(type=data['type'])

        if not data['brand'] == 'ALL':
            queryset = queryset.filter(brand__contains=data['brand'])
        return JsonResponse({'result': [item.as_dict() for item in queryset]})

JavaScript 过滤功能:

    $('.choice-link').click(function () {
    var choice = $(this).text();

    $(this).siblings().attr('id', '');

    $(this).attr('id', 'active');

    $(this).parent().parent().children('button').text(choice);

    var data = {
        'brand': $('.brand-dropdown').children('#active').attr('data-choice'),
        'type': $('.type-dropdown').children('#active').attr('data-choice')
    };

    $.ajax({
        url: '../ajax/filter/',
        data: data,
        success: function (data) {
            $('.item-block').remove();
            $.each(data.result, function (index, item) {
                if (!item.discount) {
                    var el = '<div class="item-block flex" style="flex-direction: column"><input type="hidden" value='+ JSON.stringify(item) +'><img class="img-fluid" style="box-shadow: 0 0 10px rgba(0,0,0,0.5);" src="' + item.image + '"><h6 class="item-title">' + item.rus_representation + ' "' + item.brand + '"<hr></h6><p class="flex" style="align-items: flex-start"><span class="price-tag">' + item.price + ' $</span></p><button type="button" class="item-btn btn-sm btn btn-outline-info" data-toggle="modal" data-target=".details-modal">Подробней <img style="height: 10px" "></button></div>';
                } else {
                    var el = '<div class="item-block flex" style="flex-direction: column"><input type="hidden" value='+ JSON.stringify(item) +'><img class="img-fluid" style="box-shadow: 0 0 10px rgba(0,0,0,0.5);" src="' + item.image + '"><h6 class="item-title">' + item.rus_representation + ' "' + item.brand + '"<hr></h6><p class="flex" style="align-items: flex-start"><span class="price-tag">' + item.price + ' $</span><span class="discount badge badge-danger">' + item.discount + ' $</span></p><button type="button" class="item-btn btn-sm btn btn-outline-info" data-toggle="modal" data-target=".details-modal">Подробней <img style="height: 10px" "></button></div>';
                }
                $('.items-list').children('hr').after(el)
            });

        }
    })
});

用相关数据填充模态的Java脚本函数:

$(document).on('click', '.item-btn', function () {
var data = JSON.parse($(this).siblings('input').val()); (line 54 where error message points)

$('.product-title').html(data.rus_representation + ' "<i>' + data.brand + '</i>"' + '<hr>');

if(data.description) {
    $('.product-description').text(data.description);
}else{
    $('.product-description').html('<h4>Описнаие пока не добавлено</h4>')
}

$('.carousel-inner').empty();
$.each(data.images, function (index, img) {
    if(index === 0){
        var el = '<div class="carousel-item active"><img class="d-block w-100" src="'+ img +'"></div>'
    } else {
        var el = '<div class="carousel-item"><img class="d-block w-100" src="'+ img +'"></div>'
    }

    $('.carousel-inner').append(el)
});

$('.product-brand').html('<i>' + data.brand + '</i>');
$('.product-type').text(data.rus_representation);
$('.product-season').text(data.season);

if (data.discount){
    $('.discount-in-modal').html('<span class="discount badge badge-danger" style="position: relative; top: -5px">'+ data.discount +' $</span>');
}

$('.product-price').text(data.price);

});

HTML:

            {% for item in object_list %}
            <div class="item-block flex" style="flex-direction: column">
                <input type="hidden" value="{{ item.dumped_as_dict }}">
                <img class="img-fluid" style="box-shadow: 0 0 10px rgba(0,0,0,0.5); max-height: 300px" src="{{ item.image.url }}">
                <h6 class="item-title">
                    {{item.rus_representation}} "{{item.brand}}"
                    <hr>
                </h6>
                <p class="flex" style="align-items: flex-start">
                    <span class="price-tag">{{ item.price }} $</span>
                    {% if item.discount %}
                        <span class="discount badge badge-danger">{{ item.discount }} $</span>
                    {% endif %}
                </p>
                <button type="button" class="item-btn btn-sm btn btn-outline-info" data-toggle="modal" data-target=".details-modal">Подробней <img style="height: 10px" src="{% static 'img/arrow.png' %}"></button>
            </div>
        {% endfor %}

如果做console.log(JSON.stringify(item));:

{"title":"tst","image":"/media/img/_58A1259_sm.jpg","brand":"GUCCI","type":"SK","discount":9000000,"price":9,"rus_representation":"Юбка","description":"LoL Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.","season":"","images":["/media/img/_58A1259_sm.jpg","/media/img/_58A7975_sm.jpg"]}

它应该是什么样子:

opening the modal on initial load

我有什么:

if use filtering and them trying to open details modal

从 Inspector 添加视图: For some reasons string is not fully added to value attr

【问题讨论】:

  • 我们需要在这里看到的是 JSON.parse 行正在运行的 html - 看起来它不包含有效的 json。
  • JavaScript filter function 部分,你可以在那里看到变量el,它保存了刚刚过滤结果的 html 还将添加 html 来说明它在初始加载时的样子
  • This 可能是更好的方法 - value 属性中的 json 可能无法正确解析。
  • @VladIvanyk 问题是&lt;input&gt; 的.value 中的任何内容都不是有效的JSON,但是您没有发布.value 的实际样子。
  • @Pointy 正如我上面所说,它在负责过滤$('.choice-link').click(function () { 的js 函数中可见,其中$.each 循环内有变量el。 var el = '&lt;div id="item'+ index +'" class="item-block flex" style="flex-direction: column"&gt;&lt;input type="hidden" value='+ JSON.stringify(item) +'&gt;当然如果我得到你的权利

标签: javascript python json django


【解决方案1】:

当您构建该 HTML 字符串时,您的代码会执行以下操作:

var el = '<div ... value=' + JSON.stringify(x) + ' ... >';

因此 HTML 结果将是

var el = '<div ... value={ ... } ... >';

因为“value”的属性值在生成的 HTML 源代码中没有被引用,所以就 HTML 解析器而言,JSON 中的第一个空格字符是属性值的结尾。

您至少需要包含引号:

var el = '<div ... value=\'' + JSON.stringify(x) + '\' ... >';

我还强烈建议您使用 HTML 实体编码器来编码字符串中的任何 HTML 元字符,例如

function scrubHtml(s) {
  return s.replace(/[<>'"&]/g, function(meta) {
    return "&#" + meta.charCodeAt(0) + ";";
  });
}

【讨论】:

  • 您在编辑后添加的那部分将 /[&lt;&gt;'"&amp;]/g 符号替换为 "&amp;" + meta.charCodeAt(0) + ";"; 但那个符号是什么?
  • HTML 实体表示法:&amp;nnn; 其中 nnn 部分是字符代码。这可以防止嵌入的 HTML 特殊字符混淆 HTML 解析器。结果属性值将是纯字符串;这些符号被 HTML“消化”成简单的字符。
  • @VladIvanyk 哎呀,除了我忘记了一些重要的事情!它应该是&amp;# 而不仅仅是&amp; - 现在修复答案。我很抱歉。
猜你喜欢
  • 2021-01-21
  • 1970-01-01
  • 1970-01-01
  • 2017-04-20
  • 2020-01-08
  • 2017-09-07
  • 2023-03-23
  • 1970-01-01
  • 2019-01-17
相关资源
最近更新 更多