简体   繁体   English

页面加载时从PHP调用javascript函数

[英]Call javascript function from PHP whilst page loads

I'm attempting to call a javascript function from a PHP loop. 我正在尝试从PHP循环调用javascript函数。 The call passes an id from the PHP loop and then is supposed to set a class based on whether it finds the id in a cookie. 该调用从PHP循环传递一个ID,然后应根据是否在cookie中找到该ID来设置一个类。 At the moment I am simply getting: 目前,我只是得到:

ReferenceError: getFaveClass() is not defined ReferenceError:未定义getFaveClass()

My code is the following - 我的代码如下-

?>
<script>getFaveClass(<?php echo $row->id; ?>);</script>
<?php

Is there something I am missing or a better way of doing this? 有什么我想念的东西吗?

There's nothing wrong with what you have written (although personally I'd use json_encode to ensure the value is properly handled). 您编写的内容没有任何问题(尽管就我个人而言,我将使用json_encode来确保正确处理该值)。

All the error means is that you haven't defined the getFaveClass function. 所有的错误意思是您尚未定义getFaveClass函数。 If it's in an external .js file, make sure you're including it. 如果它在外部.js文件中,请确保将其包括在内。

If the id is output, the data should be on the page when the script is executed. 如果输出了id,则执行脚本时数据应该在页面上。 Echo-ing out PHP as initial data to a JavaScript call is fine. 将PHP作为初始数据回显到JavaScript调用是可以的。 I suggest you check and see what is actually being output, rather than your PHP source, in order to debug JS errors. 我建议您检查并查看实际输出的内容,而不是PHP源代码,以便调试JS错误。

Your problem is probably what happens if $row->id == "" . 您的问题可能是如果$row->id == ""会发生什么。

Have you declared the function getFaveClass() and is there a value in the <?php echo $row->id; ?> 您是否已声明函数getFaveClass()<?php echo $row->id; ?>是否有值<?php echo $row->id; ?> <?php echo $row->id; ?>

Please check your function name to be exact including the case where you have been calling this. 请检查您的函数名称是否准确,包括调用该函数时的名称是否正确。

Just check that it should run. 只需检查它应该运行即可。 AS i can't see anything wrong with your what so ever code you have shared. 因为我看不到您共享的代码有什么问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM