页面收到AJAX响应后,JavaScript不再执行

时间:2015-01-03 04:15:35

标签: javascript php jquery html ajax

我正在做一个PHP脚本接收并发回响应的AJAX请求。在发出请求之前,我的JavaScript代码工作正常,但在从服务器收到响应后,所有JavaScript代码都变得无用。提供下面的代码只是为了说明发生了什么,并且它完美地完成了:

HTML:

<script src="http://code.jquery.com/jquery-1.9.1.min.js" type="text/javascript"></script>
<form method='post' action=''>
    <textarea cols='30' rows='5' name='test'></textarea>
    <input type='submit' value='ok' />
</form>
<div id='ajax-response'></div>

JavaScript的:

$('textarea').click(function() {
        alert('ouch!');
});
var xhr = new XMLHttpRequest;
xhr.onreadystatechange = function() {
    if (xhr.readyState == 4){
        if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304){
            document.getElementById('ajax-response').innerHTML = xhr.responseText;
        } else {
            alert("Request was unsuccessful: " + xhr.status);
        }
    }
}
$('form').submit(function(event) {
        if(typeof(FormData) != 'undefined') {
            var oform = this;
            event.preventDefault();
            xhr.open('post', '', false);
            xhr.send(new FormData(oform));
        }
});

用于处理AJAX请求的PHP脚本:

if (isset($_POST['test'])) {
    echo "<form method='post' action=''>
    <textarea cols='30' rows='5' name='test2'></textarea>
    <input type='submit' value='ok' />
    </form>";
}

收到回复并在页面中添加新表单。但在提交表单之前,当您单击textarea时,会抛出警报。当请求从服务器返回时,这不再起作用(警报只是一个示例;实际上没有执行JavaScript代码)。我整天都在这一切,解决方案将成为我的一天!

修改 Doug在下面的回答解决了我的问题,但我认为值得一提的是,由于gengkev在这个问题下面的评论,我也发现使用innerHTML不仅会删除使用它的元素的内容而且会删除其他内容。在使用新内容替换这些元素之前,构造诸如来自子元素的数据和事件处理程序。因此,当我将具有innerHTML属性的行替换为:

时,上面的代码也能正常工作
$('#ajax-response')append(xhr.responseText);

感谢您的帮助,伙计们!

4 个答案:

答案 0 :(得分:1)

好的,我已经创建了以下JSFiddle: http://jsfiddle.net/zLAht/24/

这是你想要的,对吗?

您的代码最初是Ajax请求的方式并没有替换提交中的区域,而是根据您的问题听起来像是问题。

HTML

<body>
<div id='ajax-response'>
    <form method='post' action=''>
    <textarea cols='30' rows='5' name='test'></textarea>
    <input id='sub' type='button' value='ok' />
</form>
</div>
</body>

JavaScript的:

$('textarea').click(function() {alert('ouch!');});

$('#sub').click(function(event) {
            $.ajax({
        cache:false,
         type: 'POST',
         url: '/echo/html/',
         data: {
             html:"<form method='post' action=''><textarea cols='30' rows='5' name='test2'></textarea><input type='submit' value='ok' /></form>"
         },
         success: function(data) {
             $('#ajax-response').html(data);
             $('textarea').click(function() {alert('ouch!');});
         },
         error:function(error){
             alert('there was an error');  
         },
         dataType: 'html'
     });
});

答案 1 :(得分:0)

我知道你完成所有这些事情后需要绑定元素。一种方法是使用Jquery和Use $ .live函数。您可以在

下绑定javascript中的元素
function live(eventType, elementId, cb) {
    document.addEventListener(eventType, function (event) {
        if (event.target.id === elementId) {
            cb.call(event.target, event);
        }
    });
}

live("click", "test", function (event) {




alert(this.id);
});

答案 2 :(得分:0)

如果我理解你的问题:

当你用AJAX替换html时,新的html要求你重新添加事件hoocks。因此,当您收到AJAX响应时,只需重新运行

即可
$("form").submit(...) 

钩。

答案 3 :(得分:0)

这里的问题是事件委托。当页面加载时,它会将当时的所有事件绑定到DOM中执行和可用的所有元素。由于这种行为,替换页面上的元素将删除以前绑定的事件。最好以这样一种方式处理元素,即它们的事件绑定到一个不被替换的静态父元素,以及事件可以冒泡到哪个。

那就是说,你已经包含了jQuery库,因此所有代码都将集中在那里,所以我们可以保持凝聚力:

jQuery(function($){ //setup the ready handler and alias the $ symbol as to not interfere
    //for the purpose of this example, our 'body' will be the static element.
    var $static = $('body');

    $static.on('click', 'textarea', function(){
        //the event is delegated, all textareas will receive this, present and future.
    });

    //again, we delegate the event to all forms present and future
    $static.on('submit', 'form', function(event) {
        event.preventDefault();
        if(typeof(FormData) != 'undefined') {
            var oform = this;

            //a well supported method of file uploads using jQuery's Ajax and HTML5's FormData object.
            $.ajax({
                type: $(oform).prop('method'),
                url: $(oform).prop('action'),
                contentType: false,
                processData: false,
                cache: false,
                data: new FormData(oform),
            }).on('success', function(resp){
                //do whatever on ajax success
            }).on('error', function(s,c,e){
                console.warn(s, c, e);
            });
        }
    });
});