我有一个表单,当您提交它时,它会通过 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) { new Event(e).stop(); var log = $('log_res').empty().addClass('ajax-loading'); this.send({ update: log, 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"
关于php - 如何在 Ajax 响应中调用 Javascript?即 : Close a form div upon success,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2991295/