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

前端 未结 17 1171
一生所求
一生所求 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 
        }
    });
    
    0 讨论(0)
  • 2020-12-07 22:58

    try this:

    result = $("#result", response);
    

    btw alert is a rough way to debug things, try console.log

    0 讨论(0)
  • 2020-12-07 23:00

    You should add dataType: "html" to the request. Im quite sure you wont be able to search the DOM of the returned html if it doesnt know it is html.

    0 讨论(0)
  • 2020-12-07 23:02

    To answer your question specifically, it seems to be working correctly. You said that it returns [object Object], which is what jQuery will return with the find("#result") method. It returns a jQuery element that matches the find query.

    Try getting an attribute of that object, like result.attr("id") - it should return result.


    In general, this answer depends on whether or not #result is the top level element.

    If #result is the top level element,

    <!-- #result as top level element -->
    <div id="result">
      <span>Text</span>
    </div>
    <div id="other-top-level-element"></div>
    

    find() will not work. Instead, use filter():

    var $result = $(response).filter('#result');
    

    If #result is not the top level element,

    <!-- #result not as top level element -->
    <div>
      <div id="result">
        <span>Text</span>
      </div>
    </div>
    

    find() will work:

    var $result = $(response).find('#result');
    
    0 讨论(0)
  • 2020-12-07 23:02

    You can do it in this way to find any div and get its attributes or anything you want.

    $(response).filter('#elementtobefindinresponse').attr("id");
    

    or

    $(response).filter('img#test').attr("src");
    
    0 讨论(0)
提交回复
热议问题