当返回的JSON中有双引号时,JavaScript中断

时间:2019-02-04 20:58:08

标签: javascript php json

我有一些简单的代码,可从数据库中提取一些值,然后将此数据作为JSON字符串附加到按钮上的数据属性中,以供在按下该按钮时使用。问题是,如果从数据库返回的值之一内有双引号,我猜想它会破坏JSON。

这是我的代码:

HTML:

<td
    uk-toggle="target: #entry_modal"
    class="alter_accessory"
    data-accessory='{{ json_encode(@acc) }}'
>edit</td>

@acc

的内容
Array
(
    [uid] => 23
    [title] => Lenovo 4XB0F86403 ThinkPad 512GB 2.5" Solid-State Drive
    [model] => 4XB0F86403
    [upc] => 888772069421
    [image] => https://www.disctech.com/SCASite/product_images/4XB0F86403_1000-1.jpg
    [category] => lenovo_accessory
)

注意,标题中有双引号"

这是单击此按钮时触发的javascript:

$(".alter_accessory").on('click', function() {

    var data = $(this).data('accessory');
    console.log(data);

    $('#entry_modal_title').text('Edit Accessory');

    $.each(data, function( index, value ) {
        $('#entry_' + index).val(value);
    });
});

只需循环遍历JSON并更改每个键的输入框的值

但是,当我单击按钮时,所有输入都没有填写,并且出现错误:

  

未捕获的TypeError:无法使用'in'运算符在其中搜索'length'   {“ uid”:“ 23”,“ title”:“联想4XB0F86403 ThinkPad 512GB 2.5”固态   驱动器”,“型号”:“ 4XB0F86403”,“ upc”:“ 888772069421”,“图像”:“ https://www.disctech.com/SCASite/product_images/4XB0F86403_1000-1.jpg”,“类别”:“ lenovo_accessory“}

如何解决此问题?

请求按钮的呈现HTML:

<td
    uk-toggle="target: #entry_modal"
    style="cursor: pointer; color: blue;"
    class="alter_accessory"
    data-accessory='{"uid":"23","title":"Lenovo 4XB0F86403 ThinkPad 512GB 2.5&quot; Solid-State Drive","model":"4XB0F86403","upc":"888772069421","image":"https:\/\/www.disctech.com\/SCASite\/product_images\/4XB0F86403_1000-1.jpg","category":"lenovo_accessory"}'
>edit</td>

(来自“查看源代码”)

0 个答案:

没有答案