在jQuery的阿贾克斯HTML回调导致错误换行符回调、错误、换行符、jQuery

2023-09-10 13:45:01 作者:我要向前进

我返回从 $。阿贾克斯通话一大块的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('*');