什么是解析ajax成功函数接收的数据的更清洁/更好的方法?

Aer*_*ate 2 html javascript php jquery

我正在使用ajax函数来接收数据.根据该数据,如果找不到结果,我会收到一个字符串"找不到匹配项",并带有一些html格式.如果有结果,则将数据格式化为表格,并隐藏此部分下方的"Div"部分.

现在我遇到的问题是,当我找不到结果时,我不希望这个"Div"表消失.但是为了检查是否没有结果,我将不得不比较searchCustomer.php收到的整个字符串(这是非常大的).

有更简单的方法吗?

我的ajax电话:

$('#search').click(function(e){
        $.ajax({
            type : 'GET',
            url : 'searchCustomer.php',
            dataType :'html',
            data:{
                lastName : $('#search_LN').val(),
                firstName : $('#search_FN').val(),
                phone : $('#search_PN').val()
            },
            success : function(data){
                if (data.error == true){
                    alert("there was an error in the post layer");
                } else {
                    $('#searchResults').html(data);



                if (data.text == '<br><font color='red'>No matches found</font>'){
                }else{
                var ele = document.getElementById("NewCustomerDiv");
                ele.style.display = "none";
                }
            }
        }
    });
    return false;
});
Run Code Online (Sandbox Code Playgroud)

运行fire-bug,从searchCustomer.php收到的实际数据是:

<style type="text/css">
a.resultBookButton {
    color: black;
    padding: 1px;
    border: 2px outset lightgrey;

    background: #008800;
    /* Mozilla: */
    background: -moz-linear-gradient(top, lightgrey, #FFFFFF);
    /* Chrome, Safari:*/
    background: -webkit-gradient(linear,
                left top, left bottom, from(lightgrey), to(#FFFFFF));

    text-decoration: none;
}

a:active {
    border-style: inset;
}
</style>

<br><font color='red'>No matches found</font>
Run Code Online (Sandbox Code Playgroud)

我只想检查"未找到匹配项"或是否有更好的方法找不到结果.

Bra*_*rad 5

是的,请返回JSON.您可以将响应结构化为:

{
  count: 0,
  content: "your html here"
}
Run Code Online (Sandbox Code Playgroud)

然后,您可以检查计数data.count.您的服务器需要根据找到的结果数量进行设置.

您需要在ajax调用中设置dataType属性JSON.