【问题标题】:Ajax Call Thinks That Data Contains [ ]'s when it should be emptyAjax 调用认为数据应该为空时包含 []
【发布时间】:2015-01-13 22:32:06
【问题描述】:

我有以下代码可以获取所有帖子。它可以工作,但是当没有帖子时,它仍然将 [] 作为数据发送,因此即使数据为空也不会出现任何错误。

结果总是 ["Hello"] 作为示例,但是 []s' 没有在任何地方指定.. 不知道它们为什么在那里。

ajax 代码:

 $(document).ready(function() {

        $('#btnGetPosts').click(function() {

            var recieverID = $('#RecieverID').val();

            $.ajax({
                url: "/api/Posts/GetPosts" ,
                data:{username:recieverID},
                type: "GET",
                contentType: "application/json; charset=utf-8",
                dataType: "html",

                 // it always skips error since it thinks that data contains [].
                error: function(request, status, error) {
                   alert("Error, please contact the website administrator");


                },
                 // when there is data it always shows the data like so: ["Hello"]
                success: function(data) {
                    $("#userPosts").append(data).html();

                }
            });
        });
    });

这是我的 web-api 控制器

public List<string> GetPosts(int userID)
    {


        //// uses linq to get a specific user post (all posts)
        var userPost = PostRepository.GetSpecificUserPosts(userID);

            return userPost;
        }

    }

下面是我从数据库中获取所有帖子的存储库代码。

 public List<string> GetSpecificUserPosts(int user)
    {
        using (var context = new DejtingEntities())
        {
            var result = context.Posts
                .Where(x => x.RecieverID == user)
                .Select(x => x.Body)
                .ToList();

            return result;
        }

【问题讨论】:

    标签: javascript jquery ajax asp.net-web-api


    【解决方案1】:

    您正在返回ToList() 的结果,它始终是new List();它永远不会为空。然后通过GetPosts 操作将其序列化为字符串,并以[] 的形式返回到您的JS 代码。

    即使您从操作中返回 null,您的 AJAX 代码中的 error 处理程序也不会被命中,因为将返回 200 状态代码。 error 仅在返回 other 200 以外的值时触发。

    您可以检查GetSpecificUserPosts 中的结果数量,如果没有则手动返回null,或者您可以在$.ajaxsuccess 处理程序中检查data.length

    【讨论】:

    • 嗯..你知道我该如何解决这个谜吗?
    • 或者你可以返回 204 服务器错误来触发 ajax 错误处理程序>>我不是一个 asp 人 ;)
    • ^ 或者那个,Request.CreateErrorResponse(HttpStatusCode.BadRequest)
    • ↑↑↑ 会不会比Request.CreateErrorResponse(HttpStatusCode.NoContent)更好?
    • 是的,我只是给出了创建错误响应的示例。可以返回所需的任何状态代码。我不记得 204 是什么了 :)
    【解决方案2】:

    $.ajax 错误处理程序仅在请求期间发生错误(例如 500 错误)时触发。您可能应该只考虑成功处理程序中的一个空列表,例如:

    success: function(data) {
       if(data.length) {  // if the array has elements then append them
           $('#userPosts').append(data);
       } else {  // If no elements show the alert.
            alert("Error, please contact the website administrator");  
       }
    }
    

    【讨论】:

      猜你喜欢
      • 2016-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-18
      • 1970-01-01
      • 2011-08-05
      相关资源
      最近更新 更多