-2

请参阅我的代码如下,

<div class="product_id" id="3"></div>

<?php
    $id = "<script>id = $('.product_id').attr('id');document.write(parseInt(id));</script>";
    echo "<br>";
    echo $id;
    echo "<br>";
    echo intval($id);
?>

如果我执行此代码输出是,

3

0

我不知道为什么它没有转换。我需要显示为,

3

3

谢谢

4

3 回答 3

2

PHP doesn't know what JavaScript is displaying since it is running in the browser. Look at your sourcecode and you will see what I mean. The first "3" isn't actually "3". It's JavaScript code. The Javascript code is a string which intval "casts" to a "0".

于 2013-10-22T11:54:42.477 回答
0

尝试喜欢。你需要TypeCast喜欢

echo (int)$id;
于 2013-10-22T11:52:07.067 回答
0

intval($id)试图"<script>...</script>"变成一个整数,当然失败了。看看文档(intval),“返回值”部分告诉:

成功时 var 的整数值,失败时为 0

另请记住,在打印浏览器端echo时打印服务器document.write端。现在,让我们看一下您的 PHP 代码:

<div class="product_id" id="3"></div>
<?php
    $id = "<script>id = $('.product_id').attr('id');document.write(parseInt(id));</script>";
    echo "<br>";      // prints "<br>"
    echo $id;         // prints "<script>id = $('.product_id').attr('id');document.write(parseInt(id));</script>"
    echo "<br>";      // prints "<br>"
    echo intval($id); // prints "0" (since intval failed)
?>

这是加载到浏览器中的结果 HTML:

<div class="product_id" id="3"></div>
<br>
<script>id = $('.product_id').attr('id');document.write(parseInt(id));</script>
<br>
0
于 2013-10-22T12:07:36.797 回答