我有一个表单,当您提交它时,它将通过ajax将数据进行验证以发送到另一个php脚本。验证错误会在我的表单的div中回显。如果验证通过,也会返回一条成功消息。
问题是提交并成功验证后仍显示该表单。成功后我想隐藏div。
因此,我编写了这个简单的CSS方法,当从显示表单的页面上调用该方法时,它可以很好地工作。
问题是我似乎无法通过返回的代码调用隐藏脚本。我可以像这样返回html
echo "<p>Thanks, your form passed validation and is being sent</p>";
所以我认为之后我可以简单地回呼另一行
echo "window.onload=displayDiv()";inside script tags (which I cannot get to display here)...
and that it would hide the form div.
It does not work. I am assuming that the problem is that the javascript is being returned incorrectly and not being interpreted by the browser...
How can I invoke my 'hide' script on the page via returned data from my validation script? I can echo back text but the script call is ineffective.
Thanks!
This is the script on the page with the form...
I can call it to show/hide with something like onclick="displayDiv()" while on the form but I don't want the user to invoke this... it has be called as the result of a successful validation when I write the results back to the div...
<script language="javascript" type="text/javascript">
function displayDiv()
{
var divstyle = new String();
divstyle = document.getElementById("myForm").style.display;
if(divstyle.toLowerCase()=="block" || divstyle == "")
{
document.getElementById("myForm").style.display = "none";
}
else
{
document.getElementById("myForm").style.display = "block";
}
}
</script>
PS:如果语法很重要,我正在使用mootools.js库进行表单验证。
AJAX调用为:
window.addEvent('domready',function(){
$('myForm')。addEvent('submit',function(e){
新事件(e).stop();
var log = $('log_res')。empty()。addClass('ajax-loading');
this.send({
更新:日志,
onComplete:function(){
log.removeClass('ajax-loading');
}
});
});
});
Div ID日志是显示ajax回调文本(验证错误和成功消息)和加载图形的地方
最佳答案
这是我提供所选解决方案的How to make JS execute in HTML response received using Ajax?的副本。
var response = "html\<script type=\"text/javascript\">alert(\"foo\");<\/script>html";
var reScript = /\<script.*?>(.*)<\/script>/mg;
response = response.replace(reScript, function(m,m1) {
eval(m1); //will run alert("foo");
return "";
});
alert(response); // will alert "htmlhtml"