【问题标题】:Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) at window.onload未捕获的语法错误:在 window.onload 的 JSON.parse (<anonymous>) 处的 JSON 输入意外结束
【发布时间】:2021-09-22 00:01:04
【问题描述】:

我正在使用 Tiny Editor 输入产品描述。在数据库中,我的数据类型是 BLOB。我在我的站点中到处都使用 Tiny Editor,并且具有相同的数据类型 BLOB,例如在创建博客时。它在任何地方都运行良好。

但我有一个创建食物的功能。起初,它的数据类型是 varchar,它在获取时打印 HTML TAGS。我也解决了这个问题,但是又出现了一个奇怪的问题。当我在输入产品时输入 2 个段落之间的空格时,它在获取时在前端显示了一个随机字符“rn”。

然后我将食物描述列的数据类型更改为 BLOB,因为它也适用于其他人。但是后来我遇到了这个问题

未捕获的 SyntaxError:JSON.parse () at window.onload 处的 JSON 输入意外结束”

我的食物不再显示了。

这是我的 JS

<script>

    window.onload = function()
    {
        var categories = JSON.parse('<?php echo stripslashes(json_encode($categories)); ?>');
        
        window.merchantDetailsVueApp = new Vue({
            el   : "#vueApp",
            data : function()
            {
                return {
                    categories : categories,
                    filteredCategories : categories,
                    cart       : {
                        merchant : {
                            id : "<?php echo $merchantId; ?>"
                        },
                        items    : []
                    },
                    userId     : "<?php echo isset($_SESSION['user']) ? $_SESSION['user'] : ''; ?>",
                    merchant   : null,
                    searchFood : "",
                };
            },
            computed : {
                shippingMethods : function()
                {
                    var methods = [];

                    if ("<?php echo $meta_data["delivery_option"]; ?>" === "Both")
                    {
                        methods.push("Delivery", "Pickup");
                    }
                    else
                    {
                        methods.push("<?php echo $meta_data["delivery_option"]; ?>");
                    }
                    
                    
                    return methods;
                }
            },
            methods : {
                updateCartInLocalStorage : function()
                {
                    window.localStorage.setItem("cart", JSON.stringify(this.cart));
                },
                updateCartFromStorage : function()
                {
                    this.cart = window.localStorage.getItem("cart") ? JSON.parse(window.localStorage.getItem("cart")) : null;
                },
                onAddToCartButtonClick : function(foodItem)
                {
                    if (this.cart.merchant.id.toString() !== "<?php echo $merchantId; ?>" && this.cart.items.length)
                    {
                        return alert("Please complete your existing order first.");
                    }
                    
                    this.cart.items.push(foodItem);
                    this.cart.merchant.id = "<?php echo $merchantId; ?>";
                    
                    
                    $("#myModal-" + foodItem.food_id).modal("hide");
                    this.updateCartInLocalStorage();
                    window.cartVueApp.updateCartFromStorage();
                    
                    Snackbar.show({
                        pos  : "top-center",
                        text : "Item has been added to cart successfully"
                    });
                },
                onFoodItemQuantityDecrease : function(foodItem)
                {
                    foodItem.quantity = foodItem.quantity > 1 ? foodItem.quantity - 1 : foodItem.quantity;
                    this.updateCartInLocalStorage();
                },
                onFoodItemQuantityIncrease : function(foodItem)
                {
                    foodItem.quantity += 1;
                    this.updateCartInLocalStorage();
                },
                onFoodItemVarietySelect : function(variety, foodItem)
                {
                    foodItem.selectedVariety = variety;
                    this.updateCartInLocalStorage();
                },
                onFoodItemExtraSelect : function(extras, foodItem)
                {
                    foodItem.selectedExtras = extras;
                    this.updateCartInLocalStorage();
                },
                getItemPriceRange : function(item)
                {
                    if (!item.varietyDetails.length)
                    {
                        return "$" + item.price;
                    }
                    
                    var varietyPrices = item.varietyDetails.map(function(variety)
                    {
                        return Number(variety.price);
                    })
                    .sort();
                    
                    return varietyPrices.length > 1 ? "$" + varietyPrices.shift() + " - $" + varietyPrices.pop() : "$" + varietyPrices.shift();
                },
                onSearchFoodFormSubmit : function(event)
                {
                    event.preventDefault();
                    
                    if (!this.searchFood)
                    {
                        this.filteredCategories = this.categories;
                        return;
                    }
                    
                    var criteria = this.searchFood.toLowerCase();
                    var filtered = {};
                    var category = null;
                    
                    for (var categoryId in categories)
                    {
                        category = categories[categoryId];
                        
                        if (category.name && category.name.toLowerCase().includes(criteria))
                        {
                            filtered[categoryId] = category;
                        }
                        else
                        {
                            var items = category.items.slice().filter(function(item)
                            {
                                return item.food_name.toLowerCase().includes(criteria);
                            });
                            
                            if (items.length)
                            {
                                category = Object.assign({}, category, {
                                    items : items
                                });
                                
                                filtered[categoryId] = category;
                            }
                        }
                    }
                    
                    this.filteredCategories = filtered;
                }
            },
            created : function()
            {
                this.cart = window.localStorage.getItem("cart") ? JSON.parse(window.localStorage.getItem("cart")) : this.cart;
                
                for (var category in this.categories)
                {
                    this.categories[category].items.forEach(function(item)
                    {
                        item.varietyDetails.sort(function(a, b)
                        {
                            var aPrice = Number(a.price);
                            var bPrice = Number(b.price);
                        
                            return aPrice > bPrice ? 1 : -1;
                        });
                        
                        item.extraDetails.sort(function(a, b)
                        {
                            var aPrice = Number(a.price);
                            var bPrice = Number(b.price);
                        
                            return aPrice > bPrice ? 1 : -1;
                        });
                    });
                }

                setTimeout(function()
                {
                    $("#shippingMethod").on("change", function()
                    {
                         window.cartVueApp.checkoutForm.shipping_method = this.value;
                         window.localStorage.setItem("shippingMethod", this.value);
                    });
                    
                    var shippingMethod = window.localStorage.getItem("shippingMethod");
                    
                    if (shippingMethod && $("#shippingMethod option[value='" + shippingMethod + "']").length > 0)
                    {
                        $("#shippingMethod").val(shippingMethod);
                    }
                });
            }
        });
//         $(document).on('click', 'body *', function() {
//     $('.single-pro-menu .slicknav_nav.slicknav_hidden').removeClass('active');
// });
        $('.single-pro-menu .slicknav_menu  .slicknav_btn').click(function(e) {
        e.preventDefault()
        $('.single-pro-menu .slicknav_nav.slicknav_hidden').toggleClass('active');
    });
     $('.dropdown.slicknav_parent .slicknav_item.slicknav_item.slicknav_row,.dropdown.slicknav_parent .slicknav_item.slicknav_item.slicknav_row .dropdown-toggle').click(function(e) {
        e.preventDefault()
        $('.dropdown.slicknav_parent .dropdown-menu.slicknav_hidden,.dropdown.slicknav_parent .slicknav_item.slicknav_item.slicknav_row .dropdown-toggle').toggleClass('active');
    });
    $( ".popular-item-area .anchorMenuRow .popular-item " ).click(function(){
$(this).parents().find('.row.anchorMenuRow').css( {"position": "initial","z-inedx":"0" });
});
    }

    
    
</script>
<script>
    
    $('.dropdown.slicknav_parent .slicknav_item.slicknav_item.slicknav_row,.dropdown.slicknav_parent .slicknav_item.slicknav_item.slicknav_row .dropdown-toggle').click(function(e) {
        e.preventDefault()
        $('.dropdown.slicknav_parent .dropdown-menu.slicknav_hidden,.dropdown.slicknav_parent .slicknav_item.slicknav_item.slicknav_row .dropdown-toggle').toggleClass('active');
    });
    
    $( ".popular-item-area .anchorMenuRow .popular-item " ).click(function(){
$(this).parents().find('.row.anchorMenuRow').css( {"position": "initial","z-inedx":"0" });
});
</script>

【问题讨论】:

  • 你的 $categories 里有什么?
  • 这些是食品类别。比如汉堡、比萨。卖家可以自己创建的食品类别,也可以从管理员添加的类别中进行选择。管理员添加的类别由卖家在注册时选择,然后从他的仪表板中选择。此外,他还可以从仪表板创建自己的类别。然后这些类别中包含食品
  • 我的意思是,$categories 是 PHP 数组吗?比如,$categories = ["Burger","Pizza"];
  • 它是一个数组。
  • 和这个 $row["cat_name"], "items" => [] ]; }

标签: javascript php


【解决方案1】:

似乎错误在var categories = JSON.parse('&lt;?php echo stripslashes(json_encode($categories)); ?&gt;');

如果您在 $categories 中的数组类似于

$categories1 = ["Burger", "Pizza", "Soft Drinks"];

那么你不需要使用JSON.parse。你可以这样做

var category1 = <?php echo(json_encode($categories1)); ?>;

如果您在 $categories 中的数组类似于

$categories2 = [
"cat1" =>[
    "id" =>1,
    "name" => "Burger"
    ],
"cat2" =>[
    "id" =>2,
    "name" => "Pizza"
    ],
"cat3" =>[
    "id" =>3,
    "name" => "Soft Drinks"
    ]];

那你得用JSON.parselike,

var category2 = JSON.parse('<?php echo(json_encode($categories2)); ?>');

【讨论】:

  • 我很感激。但没有一个工作。如果没有 JSON Parse,则不会显示错误,也不会显示任何产品。使用 JSON.PARSE,同样的错误。这是我的数据库ibb.co/2W97Qwk
  • 你可以试试 console.log() 并检查浏览器控制台中打印的内容。
  • 非常感谢杜拉。你指出了问题。但是我仍然为正在生成的一些随机字符修改了一些代码
  • 我通过这种方式修复了
【解决方案2】:

我通过这个修复了它。虽然主要归功于杜拉。

<script>

    window.onload = function()
    {
        var str = '<?php echo json_encode($categories);?>'
        
       var categories=str.replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\t/g, "\\t");
       
         categories = JSON.parse(categories);
        window.merchantDetailsVueApp = new Vue({
            el   : "#vueApp",
            data : function()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    • 2018-12-09
    • 2021-06-08
    • 1970-01-01
    • 2020-03-09
    • 1970-01-01
    相关资源
    最近更新 更多