从ajax jquery post响应中获取元素中的文本

时间:2022-01-14 20:16:57

Is there any way to get the text inside an element which is a response from an ajax jquery load. I need to get the text inside element which is present inside the response text from ajax page. Following is my ajax code:

是否有任何方法可以在一个元素中获取文本,该元素是来自ajax jquery负载的响应。我需要从ajax页面获得响应文本中显示的元素内部的文本。以下是我的ajax代码:

    var url = '...';
    var saveData = $.ajax({
        type: 'POST',
        url: url,
        data: {data : data},
        dataType: "text",
        success: function (resultData) {
                callback(resultData); // need to get the <h2> text here..
        }
    });
    saveData.error(function () {
        console.log("Request to API not send");
    }); 

2 个解决方案

#1


10  

You can pass HTML to jQuery and use it in the same way as if the element was on the DOM, for example with find():

您可以将HTML传递给jQuery,并以与DOM相同的方式使用它,例如find():

console.log( $(resultData).find('h2').text() );

If your HTML doesn't have a root element then you can wrap it like so:

如果HTML没有根元素,那么可以这样包装:

resultData = '<div>' + resultData + '</div>';
console.log( $(resultData).find('h2').text() );

#2


1  

How about:

如何:

$(resultData).find('h2').text()

$(resultData);(h2)。text()

#1


10  

You can pass HTML to jQuery and use it in the same way as if the element was on the DOM, for example with find():

您可以将HTML传递给jQuery,并以与DOM相同的方式使用它,例如find():

console.log( $(resultData).find('h2').text() );

If your HTML doesn't have a root element then you can wrap it like so:

如果HTML没有根元素,那么可以这样包装:

resultData = '<div>' + resultData + '</div>';
console.log( $(resultData).find('h2').text() );

#2


1  

How about:

如何:

$(resultData).find('h2').text()

$(resultData);(h2)。text()