Jquery 查找响应是否包含元素

Jquery Find if response contains element

本文关键字:包含 元素 是否 响应 查找 Jquery      更新时间:2023-09-26

如何找到响应是否包含元素形式

    $.ajax({
        url     : $(this).attr('action'),
        type    : 'POST',
        success : function(response){
            if($(response).find('form').length)
            {
                alert("hii");
            }
        }
    });

形式可以是响应的最顶层元素,也可以是中间的某个元素

$.ajax({
        url     : $(this).attr('action'),
        type    : 'POST',
        dataType: 'html', // you should set it 
                          //  if you response send html only
        success : function(response){
            if($(response).filter('form').length)
            {
                alert("hii");
            }
        }
    });

根据更新:

        ....
        dataType: 'html',
        success : function(response){
            var container = $('<div/>').append(response);
            if($(container).find('form').length)
            {
                alert("hii");
            }
        }
$.ajax({
    url     : $(this).attr('action'),
    type    : 'POST',
    success : function(response){
        var hasForm = $("<div></div>").append(response).find("form").length > 0;
        if(hasForm)
        {
            alert("hi");
        }
    }
});

数据类型:"html"强制jQuery将响应视为简单的html。我正在使用"has"函数,它将匹配的元素集减少到仅包含其中某处表单的元素集。

 $.ajax({
        url     : $(this).attr('action'),
        type    : 'POST',
        dataType : 'HTML',
        success : function(response){
           $(response).has('form').doMoreWorkHere();
        }
    });

或者,你可以写得更短

$.post($(this).attr('action'), {}
       function(response){
         $(response).has('form').doMoreWorkHere();
       }, 'html');

"响应"从何而来?这是什么格式?

我用 json 发送返回的变量:

success: function(msg){
    var obj = jQuery.parseJSON( msg ); 
    alert( obj.VARNAMEHERE );
}

或者,您可以只检查整个响应,而不是特定变量。这将使您了解如何遍历结果以找到所需的内容。

相关文章: