I get a syntax error after JQuery upgrade from 1.51 to 2

风格不统一 提交于 2019-12-24 15:27:05

问题


The code hasn't changed only the JQuery version. A simplified version of the ajax call is:

   $.ajax(
    {
        type: 'GET',
        url: MapPath($(this).attr('path')),
        cache: false,
        data: '{}',
        dataType: 'html',
        success: function (result) {
            console.log(result);
            if ($(result).filter('#feedback').length > 0) {
                $('#center').children(':first').before($(result).filter('#feedback').outerHTML());
            }
            else {
                $('#feedback').remove();
                $('#dialog').html(result);
                $('#dialog').dialog('option', 'title', 'Edit Mailbox');
                $('#dialog').dialog('open');
            }
        }
    });

Just before the if statement I log the result. It shows as expected which is a properly formatted HTML snippet. Snippet meaning it contains a DIV with child elements. When I use the selector in the if statement I get the error:

throw Error("Syntax error, unrecognized expression:

I can use the console to view the contents of result and if I try any selector I get the error. I even get the error if I just use:

$(result)

However if I modify the result and prepend <html><body> and append </body></html> then it works with no error. What changed JQuery to break this and how do I work around it? The result needs to be an HTML snippet as I am setting a container on my page to the value.


回答1:


Since I can't see your html string, I can't point out exactly what is causing it to not work with $(), however fixing it should be as easy as using $.parseHTML() on result first. If that doesn't parse it properly, the html is invalid.

result = $.parseHTML(result);
console.log(result);
if ($(result).filter('#feedback').length > 0) {
    $('#center').children(':first').before($(result).filter('#feedback').outerHTML());
}
else {
    $('#feedback').remove();
    $('#dialog').html(result);
    $('#dialog').dialog('option', 'title', 'Edit Mailbox');
    $('#dialog').dialog('open');
}


来源:https://stackoverflow.com/questions/16442763/i-get-a-syntax-error-after-jquery-upgrade-from-1-51-to-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!