Skip to main content
 首页 » 编程设计

javascript之检查函数是否在 Ajax 和 WebMethod 中返回任何数据

2024年02月06日33qq号

我开发了以下系统,可在 aspx 页面上返回无限滚动数据。它工作得很好。但是,我在检查数据库是否已到达末尾行并且没有返回数据时遇到了一个小问题。

使用以下代码,javascript 函数会在每次页面滚动到底部时继续调用 web 方法,尽管没有数据可返回。如何检查没有数据以避免那些无意义的函数调用?

$(document).ready(function () { 
    var offset = 0; 
    var fetch = 30; 
 
function Load() { 
        $.ajax({ 
            type: "POST", 
            url: "UserControls/uc_functions.aspx/LoadLatest", 
            data: "{offset :" + offset + ", fetch: " + fetch + "}", 
            contentType: "application/json; charset=utf-8", 
            dataType: "json", 
            success: function (data) { 
                if (data != "") { $('.latest').append(data.d); }  
                else {alert("no data"); completed = true; } //I never get this alert even when there is no data returned from the database 
            } 
        }) 
    }; 
 
$(window).scroll(function () { 
        if ($(window).scrollTop() + $(window).height() > $(document).height() - 10) { 
            Load(offset, fetch); 
            offset = offset + fetch; 
        } 
    }); 
}); 
 
 
[WebMethod] 
public static string LoadLatest(int offset, int fetch) 
    {   
        var LoadSql = db.Query("Exec dbo.SD_unionServices @0, @1", offset, fetch);"); 
        foreach (var item in LoadSql) 
        {  
           Load_sb.Append(item.title + "<br />");  
        } 
 
        if(LoadSql.Count() > 0) 
        return Load_sb.ToString(); 
        else 
        return string.Empty; 
    } 

更新 为了检查数据是否为空,我使用了 data.d 而不是 data

 if (data.d != "") { $('.latest').append(data.d); } 

代替

 if (data != "") { $('.latest').append(data.d); } 

请您参考如下方法:

改进它以在没有可用数据时返回 string.Empty。

public static string LoadLatest(int offset, int fetch) 
{   
    var LoadSql = db.Query("Exec dbo.SD_unionServices @0, @1", offset, fetch);"); 
    foreach (var item in LoadSql) 
    {  
       Load_sb.Append(item.title + "<br />");  
    } 
 
    if(Load_sb.Count() > 0) 
       return Load_sb.ToString(); 
    else 
       return string.Empty; 
 
}