英文:
Explode doesn't work with a string coming from JS
问题
<script>
// 当按钮被点击时
let tags = ''foo,bar'';
elem.innerHTML += `<x-post tags="${tags}"></x-post>`
</script>
@php
var_dump($tags); // string(9) "foo,bar"
$tags = explode(',',$tags); // 分割字符串
echo "<br>";
var_dump($tags); // array(1) { [0] => string(9) "foo,bar"}
@endphp
英文:
Javascript
<script>
// when button clicked
let tags = 'foo,bar';
elem.innerHTML += `<x-post tags="${tags}"></x-post>`
</script>
post.blade.php
@php
var_dump($tags); // string(9) "foo,bar"
$tags = explode(',',$tags); // exploding
echo "<br>";
var_dump($tags); // array(1) { [0] => string(9) "foo,bar"}
@endphp
How can I fix it? And why this is working correctly when I write tags="foo,bar"
?
Expecting: array with foo and bar.
Tryed: JSON.stringify()
, array, array with JSON.stringify()
.
Actually, I'm sending a post with tags via ajax so that they load after clicking on the button, like pagination. It works without tags, but such a problem has arisen with them.
Maybe you know how i can normally send an array to a blade component like in php?
答案1
得分: -1
这可以通过创建一个额外的组件来解决。毕竟,问题在于我试图在php中处理字符串。
let html = '';
html += `<x-post title=${post.title}>${post.content}`;
tags.forEach(function(tag){
html += `<x-tag>${tag.name}</x-tag>`;
})
html += `</x-post>`;
elem.innerHTML += html;
英文:
This can be solved by creating an additional component.
After all, the problem is that I tried to process the string in php
let html = '';
html += `<x-post title=${post.title}>${post.content}`;
tags.forEach(function(tag){
html += `<x-tag>${tag.name}</x-tag>`;
})
html += `</x-post>`;
elem.innerHTML += html;
答案2
得分: -2
你使用双引号将 tags
作为字符串文字发送,即 <x-post tags="${tags}"></x-post>
,因此返回的是 $tags
的总长度为9。
尝试不使用双引号,
<script>
// 在JS中
let tags = 'foo,bar';
elem.innerHTML += `<x-post tags=${tags}></x-post>`
</script>
// post.blade.php
@php
var_dump($tags); // string(7) "foo,bar"
$tags = explode(',',$tags); // 分割
echo "<br>";
var_dump($tags); // array(2) { [0]=> string(3) "foo" [1]=> string(3) "bar" }
@endphp
希望这有所帮助
英文:
You're sending tags
in string literal with double quotes i.e. <x-post tags="${tags}"></x-post>
and therefore it's returning the total length of $tags
9.
Try without double quotes,
<script>
//in JS
let tags = 'foo,bar';
elem.innerHTML += `<x-post tags=${tags}></x-post>`
</script>
// post.blade.php
@php
var_dump($tags); // string(7) "foo,bar"
$tags = explode(',',$tags); // exploding
echo "<br>";
var_dump($tags); // array(2) { [0]=> string(3) "foo" [1]=> string(3) "bar" }
@endphp
Hope it wll help
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论