2

我有一个$.ajax调用 asp.net Webmethod 的函数。

当没有数据返回时,我想用一个窗口提醒用户。

这是我在 FireBug 中看到的返回 JSON 字符串:

{"d": "[]"}

以下是该功能的片段 -

success: function (msg) {
    var data = eval(msg.d);
    var i = 0;
    var Name;
    for (i = 0; i < data.length; i++) {
        if (data.length == 0) {
            alert('oops no data has been returned sorry.');
        } else {
            //do the good stuff
        }
    }
},
4

2 回答 2

1
function webMethodCall(){
return $.getJSON('myURL',{/*my data*/}).done(function(msg){
 if(!msg || !msg.d.length){
         alert('Emptydata!')
    }
});
};  
于 2013-04-09T16:33:12.440 回答
1

if-else语句移到循环外for,将for循环移到else分支内:

if (data.length == 0) {
    alert('oops no data has been returned sorry.');
} else {
    for (i = 0; i < data.length; i++) {
        //do the good stuff
    }
}

在您的代码中,如果为空,if则永远不会执行该语句,因为永远不会执行循环体(is )。datafor0 < 0false


其他问题:

我建议修复您的 JSON 生成过程。如果msg.d应该包含数组,则不要为其分配字符串。你的 JSON 应该看起来像

{"d": []}

似乎您以某种方式对数据进行了双重编码。

如果你不这样做,我至少会使用JSON.parse而不是eval.

于 2013-04-09T16:40:44.917 回答