jQuery .find() on data from .ajax() call is returning “[object Object]” instead of div

前端 未结 17 1167
一生所求
一生所求 2020-12-07 22:05

Trying to find div element with id=\"result\" in returned data from .ajax() using .find(). Unfortunately, alert(res

17条回答
  •  囚心锁ツ
    2020-12-07 22:56

    The thing is that your ajax response is returning a string, so if you use directly $(response) it would return JQUERY: Uncaught Error: Syntax error, unrecognized expression in the console. In order to use it properly you need to use first a JQUERY built-in function called $.parseHTML(response). As what the function name implies you need to parse the string first as an html object. Just like this in your case:

    $.ajax({
        url: url, 
        cache: false,
        success: function(response) {
            var parsedResponse = $.parseHTML(response);
            var result = $(parsedResponse).find("#result");
    
            alert(response); // returns as string in console
            alert(parsedResponse); // returns as object HTML in console
            alert(result); // returns as object that has an id named result 
        }
    });
    

提交回复
热议问题