Ajax回调以获取数组结果

Ajax回调以获取数组结果

本文介绍了jQuery Ajax回调以获取数组结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下jQuery Ajax场景,其中Web方法返回字符串集合.

I have following jQuery Ajax scenario in which a webmethod returns a collection of strings.

  1. 该集合可以为空
  2. 该集合可以为非空但记录为零.
  3. 该收藏集中有一个或多个记录

以下代码可以正常工作.它使用 jQuery.isEmptyObject .如果不是Plain Object,建议不要使用isEmptyObject().

The following code works fine. It uses jQuery.isEmptyObject. It is advised not to use isEmptyObject() when it is not a Plain Object.

在不使用isEmptyObject()的情况下如何处理结果?

How can we handle the result without using isEmptyObject() ?

注意:ajax的结果"以不简单的"形式出现.

Note: The ajax "result" is coming as "not plain".

参考:

  1. 对象是否为空?
  2. JavaScript的hasOwnProperty()方法比IN运算符更一致
  1. Is object empty?
  2. Javascript's hasOwnProperty() Method Is More Consistent Than The IN Operator

代码

//Callback Function
function displayResultForLog(result)
{


if (result.hasOwnProperty("d"))
{
    result = result.d
}


if ($.isPlainObject(result)) {
    alert('plain object');
}
else
{
    alert('not plain');
}

if($.isEmptyObject(result))
{
    //Method returned null
    $(requiredTable).append('No data found for the search criteria.');
}
else
{

    if (result.hasOwnProperty('length'))
    {

        //Set the values in HTML
        for (i = 0; i < result.length; i++)
        {
            var sentDate = result[i];
        }
    }

    else
    {
      //Method returned non-null object; but there is no rows in that
      $(requiredTable).append('No data found for the search criteria.');
    }

  }

 }

function setReportTable(receivedContext) {

var searchInput = '111';
$.ajax(
        {
            type: "POST",
            url: "ReportList.aspx/GetReportsSentWithinDates",
            data: '{"searchInput": "' + searchInput + '"}',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            context: receivedContext, //CONTEXT
            success: displayResultForLog

        }
        );
 }

推荐答案

目前,我正在使用以下内容.有任何改进建议吗?

At present I am using the following. Any improvement suggestions?

 function displayResultForLog(result)
 {
   if (result.hasOwnProperty("d")) {
       result = result.d
   }

if (result !== undefined && result != null )
{
    if (result.hasOwnProperty('length'))
    {
        if (result.length >= 1)
        {
            for (i = 0; i < result.length; i++) {

                var sentDate = result[i];

            }
        }
        else
        {
            $(requiredTable).append('Length is 0');
        }
    }

    else
    {
        $(requiredTable).append('Length is not available.');
    }

}
else
{
    $(requiredTable).append('Result is null.');
}
}

此处未定义的参考信息 JavaScript未定义属性

Reference for undefined is here JavaScript undefined Property

这篇关于jQuery Ajax回调以获取数组结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 04:47