php - 如何在 Ajax 响应中调用 Javascript?即 : Close a form div upon success

标签 php javascript ajax

我有一个表单,当您提交它时,它会通过 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/

相关文章:

php - 电子邮件脚本报告成功,但电子邮件没有出现在我的收件箱中

javascript - jQuery 按需加载 TinyMCE 4

javascript - 如何_真正_删除/清除/忘记 JavaScript 中的对象实例?

javascript - 如何根据每次迭代更改for循环中的图像

ajax - 我的 javascript/jquery 代码有什么问题吗?

php - JQuery Ajax 加载的内容无法从父级调用 PHP 变量

php - 如何使用 JavaScript 或 jQuery 从下拉列表中选择多个值并将其添加到另一个字段

PHP Pear Mail 返回 fatal error : Failed opening required 'Mail.php'

php - 如何使用zf2向mysql插入数据?

javascript - 延迟 Web 安装横幅