我在尝试从PHP激活jQuery函数时遇到问题。
以下是我自己的测试版本。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Welcome to temp index</title>
<link rel="stylesheet" href="style.css" type="text/css" />
<script type="text/javascript" src="scripts/jquery-1.8.3.min[2].js"></script>
<script type="text/javascript">
$(document).ready(function() {
//posts info into the userinfo.php file
$.post('userinfo.php', { activate:"colourchange"}, function(data){
$('report').html(data);
});
//the function which is meant to be activated from the php file
function colourchange(){
document.body.style.backgroundColor = 'green';
};
});
</script>
</head>
<body>
<h1>hello</h1>
<div id="report">
</div>
</body>
</html>
<?php
if( $_REQUEST["activate"])
{
$activate = $_REQUEST['activate'];
};
if($activate == 'colourchange')
{
// This is the code that I believe not to be working as this isn't
// activating the jQuery function to work. (The page background isn't changing colour)
echo "<script>colourchange(); </script>";
};
?>
非常感谢任何知道该做什么的人。
我现在试过......
<?php
require 'userinfo.php';
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Welcome to temp index</title>
<link rel="stylesheet" href="style.css" type="text/css" />
<script type="text/javascript" src="scripts/jquery-1.8.3.min[2].js"></script>
<script type="text/javascript">
function colourchange(){
document.body.style.backgroundColor = 'green';
};
$(document).ready(function() {
$.post('userinfo.php', { activate:"colourchange"}, function(data){
$('report').html(data);
});
});
</script>
</head>
<body>
<h1>hello</h1>
<div id="report">
</div>
</body>
</html>
并且PHP索引文件是......
<?php
if( $_REQUEST["activate"])
{
$activate = $_REQUEST['activate'];
};
if($activate=='colourchange')
{
echo "colourchange();";
};
?>
答案 0 :(得分:1)
我并不完全理解你为什么要使用PHP来执行jQuery函数 - 也许这只是一个过于简单的例子。假设您的主要目标是让PHP响应触发特定的Javascript函数(并且可能允许PHP响应触发几个不同的响应),您可以执行以下操作:
首先从
更改回调function(data){
$('report').html(data);
}
类似于:
function(data) {
if (data.indexOf("colourchange") >= 0) { // php page returned "colorchange" or a string containing "colourchange"
colourchange();
} else if (data.indexOf("moodchange") >= 0) {
moodchange(); /// etc... you can add more trigger functions here
}
}
第二个......让你的PHP页面返回“colourchange”而不是HTML片段:
if($activate == 'colourchange')
{
echo "colourchange";
};
这有帮助吗?
答案 1 :(得分:0)
你可以尝试这个 - 例子在成功时调用jquery函数
$.ajax({
url: //the url,
data: //the data,
type: "POST",
success: function(data){
if(data == "ok"){
colorChange();
}
}
});
这里的数据将是php代码返回的成功结果..
您可以根据返回的数据调用函数