为什么这段代码不起作用?
谁能告诉我为什么这段代码不起作用?
<?php $err=1; ?>
<img src="334234234234234.gif" onError="<?php $err=0; ?>" />
<?php echo "<br />" . $err; ?>
即使图像存在,onerror 仍然会执行。 为什么?
Can anyone tell me why this code won't work?
<?php $err=1; ?>
<img src="334234234234234.gif" onError="<?php $err=0; ?>" />
<?php echo "<br />" . $err; ?>
Even when the image exists, the onerror is still executed. Why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
HTML 无法设置 PHP 变量。 这些只能在服务器上进行设置。 IMG 标记的 onError 方法无法访问 PHP 变量。
页面生命周期:
请注意,您正在尝试将项目 3 与项目 1 组合起来,这在语义上无法完成。
执行您尝试执行的操作的唯一方法是将 javascript 方法附加到该事件,并在运行 onError 方法时与服务器进行通信。 但这可能比您习惯的要复杂一些。
HTML cannot set PHP variables. Those can only be set while on the server. The onError method of the IMG tag has no access to PHP variables.
The page life-cycle:
Note, you're attempting to combine item 3 with item 1, which cannot be done semantically.
The only way to do what you're attempting would be to attach a javascript method to that event, and communicate to the server when and if the onError method is ran. But this is likely going to be a bit more complicated than you're use to.
由于 php 是服务器端代码,因此
都会被执行。 您需要使用其他方法或 Javascript(或其他客户端代码)来执行此操作。
如果您只想在图像未加载时将变量打印到屏幕上,则可以使用
onError="alert('ERROR: Image did not load');"
来创建一个弹出框(或者您可以使用 javascript 修改页面上的 html),但如果您想与服务器对话,则必须使用 javascript 提交表单或使用 AJAX 方法。Since php is server side code, the
<?php $err=0; ?>
will get executed whether or not onError actually happens. You'll want to use someother method, or Javascript (or another client side code) to do that.If all you are wanting to do is print out a variable to the screen if the image doesn't load, you can use
onError="alert('ERROR: Image did not load');"
to create a popup box (or you can use javascript to modify the html on the page), but if you want to talk to the server, you'll have to either submit a form with javascript or use an AJAX method.您的代码将始终产生以下输出:
onError
JavaScript 处理程序为空,因为其中的 php 代码不产生任何输出。您发布的代码是实际代码还是简化代码? 目前尚不清楚您想要实现什么目标。
Your code will always produce this output:
The
onError
JavaScript handler is empty because the php code inside it produces no output.Is the code you posted actual code or simplified code? It's not clear what you're trying to accomplish.
如果您要检查文件是否存在,PHP 提供了一个很好的函数
http://us.php.net/file_exists
修改后的页面示例。
来回答你的问题。
onError 永远不会被执行。 它似乎执行了,因为您在脚本末尾显式输出了 $err 变量。 如果您使用上面的代码,您可以实现我认为的预期结果,而无需依赖 JavaScript 事件。
If you are checking for the existence of a file PHP offers a nice function
http://us.php.net/file_exists
Modified example from page.
To answer your question.
The onError is never executed. It appears to execute because you explicitly output the $err variable at the end of the script. If you use the above code you can achieve what I believe was the intended result without relying on a JavaScript event.