我正在尝试使用jQuery来刷新<div>
,以调用包含javascript的PHP脚本。
刷新后,页面会加载,但javascript不会执行。
我的问题是我不使用javascript函数,而是简单地编写代码。
我知道我必须使用.on()
或.live()
,但不知道如何使用。
我正在尝试调用的页面:
require 'connexion.php';
$statement = $connexion->prepare("SELECT * FROM table");
$statement->execute();
echo "<div id='refreshdiv'>";
// generating content
if (isset($statement))
{
while($data = $statement->fetch())
{
?>
<script language="javascript">
var str_in;
var str_out = "";
var num_in;
var num_out = "";
var e = "Enter Text!";
var num_out = <?php echo json_encode($data['message']); ?>;
str_out = "";
for(i = 0; i < num_out.length; i += 2) {
num_in = parseInt(num_out.substr(i,[2])) + 23;
num_in = unescape('%' + num_in.toString(16));
str_out += num_in;
}
message = unescape(str_out);
</script>
<?php
if ($data['user'] == 'user1')
{
echo "<p class='man'>".'Le '.$data['date'].' '.$data['user'].' à dit:'.'<br>'."\n" ;
?><script language="javascript">document.write(message);</script><?php
echo "</p>"."\n" ;
}
else
{
echo "<p class='woman'>".'Le '.$data['date'].' '.$data['user'].' à dit:'.'<br>'."\n" ;
?><script language="javascript">document.write(message);</script><?php
echo "</p>"."\n" ;
}
}
}
echo '</div>';
?>
主页:
<script>
function autoRefresh_div()
{
$("#refreshdiv").load("refreshpage.php");
}
setInterval('autoRefresh_div()', 5000);
</script>
<div id='refreshdiv'><div>
发布于 2014-11-02 06:51:55
在我看来,绝对不需要在使用AJAX调用的页面上使用JS。所有这些东西都只能通过PHP呈现,这就是你应该做的。
即使不是这样,从AJAX响应运行JS代码也是非常不安全和具有挑战性的。您必须分离JS代码(可能在JSON变量中),然后对其运行eval() ...同样,非常非常不安全,不推荐使用。
如果在AJAX调用之后仍然希望使用JS,请在主页上定义函数,并将从AJAX调用中获得的参数传递给它。如下所示:
function autoRefresh_div() {
$.get("refreshpage.php", function(res){
var content = res.htmlContent; // say this is the content for the div
var jsParam = res.jsParam; // and this is the JS parameter(s)
$("#refreshdiv").html(content);
handleAjax(jsParam);
});
}
function handleAjax(params) {
/// do stuff here
}
https://stackoverflow.com/questions/26691364
复制相似问题