![](/img/trans.png)
[英]JSON.parse throws syntax error when trying to parse escaped double quote
[英]"Unexpected identifier" error in Javascript when trying to parse JSON with escaped single quote
在我的 Laravel 應用程序中,我將一個 JSON 對象傳遞給一個 Vue 組件:
<search v-bind:library="'{{ json_encode(language_library()) }}'"></search>
language_library()
,出於測試目的,只返回一行:
{"you_dont_have_subscription":"You don\\'t have an active subscription right now."}
如您所見,字符串中的單引號被轉義了。 但是,Vue 拋出此錯誤:
[Vue warn]: Error compiling template:
invalid expression: Unexpected identifier in
'{"you_dont_have_subscription":"You don\\'t have an active subscription right now."}'
Raw expression: v-bind:library="'{"you_dont_have_subscription":"You don\\'t have an active subscription right now."}'"
我不明白為什么會出現這個問題。 它是雙引號內的單引號並且它也被轉義了(在 PHP 后端使用addslashes()
)。 如果不是這樣,我怎么能在我的 JSON 中有一個包含引號的字符串?
如果,而不是addslahes,我手動做這樣的事情......
str_replace("'", "\'", $string)
...我仍然遇到同樣的錯誤,在 JSON 中的引號前有兩個反斜杠。
你只需要像下面的例子一樣編寫search
標簽:
<search v-bind:library="'{{ json_encode(language_library(), JSON_HEX_QUOT | JSON_HEX_APOS) }}'"></search>
編輯
根據Laravel 的文檔示例,您應該刪除單引號。
<option {{ $isSelected($value) ? 'selected="selected"' : '' }} value="{{ $value }}">
{{ $label }}
</option>
所以你的搜索標簽會變成這樣:
<search v-bind:library="{{ json_encode(language_library(), JSON_HEX_QUOT | JSON_HEX_APOS) }}"></search>
// or you could declare a variable and assign `json_encode` to it
<?php $json = json_encode(language_library(), JSON_HEX_QUOT | JSON_HEX_APOS); ?>
<search v-bind:library="{{ $json }}"></search>
這是常見的錯誤。 它與引用無關,雙引號會導致此錯誤。 為什么? 查看您對 prop 的輸入
v-bind:library="'{"you_dont_have_subscription":"You don\\'t have an active subscription right now."}'"
這意味着 js 不知道為什么 library prop 以v-bind:library="'{"
結尾,所以使用引號而不是 dbl 引號。 像這樣:
<search :library='@json(language_library())'></search>
嘗試它可能會在我身上發生同樣的事情
我用{!! $value !! }}
{!! $value !! }}
<search v-bind:library="{!! json_encode(language_library()) !!}"></search>
答:你沒有必要額外'
解釋:記住json_encode
將返回{}
並且 Laravel 將在{{ }}
回顯它然后作為對象本身傳遞並編譯到 javascript {}
編輯:
使用額外的'
將被 javascript 視為結束字符串
編碼示例
<search v-bind:library="{{ json_encode(language_library()) }}"></search>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.