我需要一种方法来在php的Jquery请求期间调用Javascript函数。
我的网站的所有重新请求都是通过函数从Jquery进行的:Post()、get()和getJson(),但当尝试从php调用javascript时,什么都不会发生。:(
如果我使用html提交,javascript运行良好。
那么我想知道在这种情况下,我需要为javascript工作做些什么?
示例I
我在index.php:中的php代码
echo "<script>Message();</script>";
我的JavaScript:
function Message()
{
alert('JavaScript Executing!');
}
我的Jquery代码:
function Save()
{
$.post
(
'index.php',
{
Action: 'Save'
}
)
}
Html按钮:
<form>
<br><input type="button" value="Massage with Jquery!" onclick="Save()"><br>
<br><input type="submit" value="Message without Jquery!"><br>
</form>
我想点击按钮"Message with Jquery",然后到我的php调用函数javascript"Message"。
证明需要:我可以在jQuery回调中直接调用这个JavaScript。问题是,谁知道什么时候运行这个JavaScript Message(),就是客户端。:?jQuery POST有几个客户端?我的视图是可重用的,只有index.php知道应该执行还是不执行哪个javascript函数。
示例II
出现问题的其他示例:
新.tpl
<script src="js/jquery.js" type="text/javascript"></script>
<script>
function Save()
{
$.post
(
'index.php',
{
Action: 'Save'
}
)
}
function Message()
{
alert('JavaScript Executing!');
}
</script>
<form>
<br><input type="button" value="Massage with Jquery!" onclick="Save()"><br>
<br><input type="submit" value="Message without Jquery!"><br>
</form>
index.php
<?php
if( !isset($_POST['Action']))
{
require_once($_SERVER['DOCUMENT_ROOT']."MeuTreinamentoPHP/smarty/templates/Controler/MySmarty.php");
$MySmarty=MySmarty::getInstance();
$MySmarty->Open('new.tpl');
}
echo "<script>Message();</script>";//It is essential that the JavaScript is called in index in this case. :?
?>
谢谢大家!
您在这里有一个误解。
JQuery是一个Javascript库。两者都在客户端(浏览器)上运行。
PHP在web服务器上运行。因此不运行Javascript。
您可以让Javascript从web服务器请求JSON等,这可能会使用PHP 来传递数据
您可以回显JS
<?php
echo '<script>alert("JS in PHP.");</script>';
?>
你的意思是?此代码未经测试
mainphp.php(或任何文件名)
<script>
function save(){
//Lets you know you will be executing
alert('JavaScript Executing!');
//Get Value
var postVal = $("#ButtonValue").val();
//Post the inputs data to the index file, to save maybe?
//Then post back what you saved?
$.post("index.php", { "postVal": postVal },
function(data) {
alert(data);
});
}
</script>
//You Have this form, I added an ID
<?php
echo '
<form>
<br><input id="ButtonValue" type="button" value="Massage with Jquery!" onclick="Save()"><br>
<br><input type="submit" value="Message without Jquery!"><br>
</form>';
?>
Index.php将具有
<?php
$postVal = $_POST['postVal'];
echo $postVal;
?>
这将在您发布
所以您想告诉javascript在完成ajaxy魔术后该做什么。
$.post("index.php",
{Action: 'Save'},
function(data) { eval(data); }
)
这将有效地执行您从服务器返回的任何javascript在php中,不要发送脚本标记,只发送要执行的代码:
echo "Message();"
更简单、更好的解决方案是从服务器返回命令代码,并在客户端中根据它们进行操作。这样你就可以把所有的javascript放在它应该放的地方。