![](/img/trans.png)
[英]Redirect form dependent url to open in an Iframe on an html or within the php file
[英]HTML form stop redirect and allow PHP to call JavaScript from within the HTML file
我希望HTML页面上的表单在发送后不刷新,这已经完成,但是我也想允许PHP文件中的echo
命令能够从HTML文件中调用JavaScript。 。
到目前为止,还没有执行所有的echo
命令,这不是我期望的。
以下是HTML和PHP文件中的一些代码:
HTML:
<script type="text/javascript">
function functionInFile() {
alert("recieved");
}
$(function() {
$(".postform").submit(function() {
var content = $(this).serialize();
$.post('signup.php?', content);
return false;
});
});
</script>
和PHP:
echo '<script type=\'text/javascript\'>functionInFile()</script>';
因此,基本上,我希望PHP文件能够调用HTML文件中的函数,而在单击“提交”时不被重定向。
任何帮助表示赞赏。
您可以使用$.post()
的成功回调函数来执行PHP返回的函数。 尝试这个:
PHP
// do some stuff with the posted data
echo 'functionInFile'; // name of js function to execute in calling page
jQuery的
function functionInFile() {
alert("recieved");
}
$(function() {
$(".postform").submit(function() {
$.post(
'signup.php?',
$(this).serialize(),
function(func) {
window[func]();
},
'text'
);
return false;
});
});
最好使用post
的回调函数
jQuery.post(url [,data] [,success(data,textStatus,jqXHR)] [,dataType])
因此,您可以在回复或预先确定的登录onsusccess
执行任何代码
$.post( 'signup.php?', content,
function( data ) {
//data contains the reply of the post so you can
//exec the code like this using JavaScript
//altogether eval is frowned upon because it is high overhead and opens
//opens up to code injection or whatever
//eval(data);
//so you just execute whatever method you need
functionInFile();
//or you reply from server in json and converto tobject
//reply: {'executeFunction': true}
var obj = jQuery.parseJSON(data);
if (data.executeFunction == true) { functionInFile(); }
}
);
为了使PHP回显正常工作。 该页面必须重新加载,因为它是服务器端。
网页周期是服务器端,然后是客户端。
[服务器]-> [客户端-> AJAX到服务器->服务器回复连接]
您似乎正在发送正确的<script>
标签。 但是XHR返回值被视为数据,而不是可执行代码。 幸运的是,jQuery有代码可检查是否将<script>
标记插入dom并执行。 您应该能够做到:
$.post('signup.php?', content, function(html) {$(document).append(html);});
然后您的脚本将执行。
(不过,我建议您以其他方式实现这一点。我已经开发了在AJAX调用中发送大量javascript的应用程序,调试起来很麻烦。最好将JSON对象与字符串用于下一个操作,然后将“已批准”操作的对象保留为字符串->函数查找表。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.