在jQuery的阿贾克斯HTML回调导致错误换行符 [英] Line breaks in jQuery ajax html callback cause errors

查看:127
本文介绍了在jQuery的阿贾克斯HTML回调导致错误换行符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我返回从 $。阿贾克斯通话一大块的HTML。从PHP未来的字符串有两个换行符开头,如

I am returning a large chunk of HTML from an $.ajax call. The string coming from PHP has two line breaks at the beginning, e.g.

$data = "

<div>
     <p>Here is some text</p>
</div>";

下面是 $ AJAX 电话:

$('form#form_id').submit(function(e){
    e.preventDefault();
    $form = $(this);
    $.ajax({
        url: $form.attr('action'),
        type: $form.attr('method'),
        data: $form.serialize(),
        dataType: 'html',
        success: function(data) {
            var $html = $($.parseHTML(data));
            $html.appendTo('#container_id').hide().fadeIn(300);
        }
    });
});

一切正常,直到我添加了 .hide()淡入(300)此时它抛出:类型错误:未定义不一个对象(评估'hooks.cur = FN')的jquery.js:1925年。如果我删除换行符它的工作原理。我现在用的是 $ parseHTML 因为jQuery说:

Everything works until I add the .hide().fadeIn(300) at which point it throws: TypeError: 'undefined' is not an object (evaluating 'hooks.cur = fn') jquery.js:1925. If I remove the line breaks it works. I am using the $.parseHTML because jQuery says:

如果字符串是已知的HTML,但可能会启动任意文本   不是HTML标签,将它传递给jQuery.parseHTML(),它会返回一个   DOM节点阵列重新presenting的标记。这个jQuery集合可以是   从这个创建的,例如:$($ parseHTML(htmlString))

If a string is known to be HTML but may start with arbitrary text that is not an HTML tag, pass it to jQuery.parseHTML() which will return an array of DOM nodes representing the markup. A jQuery collection can be created from this, for example: $($.parseHTML(htmlString)).

任何想法是怎么回事?

推荐答案

这个问题似乎是由集合中的文本节点使你可以过滤它与 .filter('*')

The problem seems to be caused by the text node in the collection you can filter it out with .filter('*')

var $html = $($.parseHTML(data)).filter('*');

这篇关于在jQuery的阿贾克斯HTML回调导致错误换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆