简体   繁体   English

有什么更干净/更好的方法来解析ajax成功函数接收到的数据?

[英]What is a cleaner / better way of parsing data received by an ajax success function?

I am using an ajax function to receive data. 我正在使用ajax函数来接收数据。 Based on that data, if results are not found I receive a string "No matches found" with some html formatting. 根据该数据,如果未找到结果,则会收到带有某些html格式的字符串“找不到匹配项”。 If there are results, data is formatted into a table and a "Div" section underneath this section is hidden. 如果有结果,则将数据格式化为表格,并隐藏该部分下面的“ Div”部分。

Now the issue I am having is, when I find no results, i do not want this "Div" table to disappear.But to check if there are no results, I would have to compare the whole string received by the searchCustomer.php (which is very large). 现在我遇到的问题是,当我找不到任何结果时,我不希望该“ Div”表消失。但是要检查是否没有结果,我必须比较searchCustomer.php(这是非常大的)。

Is there an easier way of doing this? 有更简单的方法吗?

My ajax call: 我的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;
});

Running fire-bug, The actual data received from searchCustomer.php is: 运行萤火虫,从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>

I just want to check for "No matches found" or if there is a better way of finding no results. 我只想检查“找不到匹配项”,或者是否有更好的找不到结果的方法。

Yes, return JSON instead. 是的,请返回JSON。 You can structure the response to be: 您可以将响应结构为:

{
  count: 0,
  content: "your html here"
}

You can then check the count through data.count . 然后,您可以通过data.count检查计数。 Your server will need to set this based on the number of results found. 您的服务器将需要根据找到的结果数进行设置。

You will want to set the dataType property in the ajax call to JSON . 您将需要在ajax调用中将dataType属性设置为JSON

I disagree with Brad, converting to JSON would be a pain because all your HTML which uses quotes all the time would have to have those quotes escaped in order to work in a JSON string, which can present an annoyance at best and accidentally trigger errors for invalid JSON at worst. 我不同意Brad的观点,将其转换为JSON会很痛苦,因为所有一直使用引号的HTML都必须转义这些引号才能在JSON字符串中工作,这最多可能会带来烦恼并意外触发错误最糟糕的是无效的JSON。

The ideal solution is changing what those pages return. 理想的解决方案是更改这些页面返回的内容。 Return the full HTML if items found, return "0" or "" if nothing is found, and then check for those returns. 如果找到项目,则返回完整的HTML;如果未找到任何内容,则返回“ 0”或“”,然后检查这些返回。

If you can't change what is returned from the AJAX call, perhaps just do an (returnedData.indexOf(" 如果您无法更改AJAX调用返回的内容,则只需执行(returnedData.indexOf(“

Easy peasy. 十分简单。

EDIT: 编辑:

$.ajax({
      ... other setting ...
        success : function(data){
           (data.indexOf('<table') == -1){
                //there was a table in the returned data
           } else {
                // ...
           }
        }
      });

AJAX responses should contain raw data that is in an easily parse-able format, such as JSON or XML. AJAX响应应包含易于解析的格式的原始数据,例如JSON或XML。 Upon receiving the response, the AJAX success handler should then parse the response and generate the necessary HTML to display. 收到响应后,AJAX成功处理程序应解析响应并生成必要的HTML以显示。 searchCustomer.php should not be generating the HTML...your success handler should. searchCustomer.php不应生成HTML ...您的成功处理程序应该。

If designed in this way, it gives you the flexibility to display the data however you want, so you can re-use this AJAX function anywhere in your website (or even make it publically available for others on the Internet to use). 如果以此方式设计,它可以让您灵活地显示所需的数据,因此您可以在网站的任何位置重复使用此AJAX功能(甚至可以将其公开提供给Internet上的其他人使用)。

JSON: JSON:

{
  results: [
    "result1",
    "result2"
  ]
}

XML: XML:

<results>
  <result>result1</result>
  <result>result2</result>
</results>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM