开发者

Why can't JQuery load my resource?

I have the following script in an page called ajax.aspx page:

 <script type="text/javascript">
    $(document).ready(function () {

        var nameFoundMessage = $('#nameFoundMessage');
        var nameInput = $('#name');

        nameFoundMessage.hide();

        nameInput.blur(function () {


            if ($(this).val()) {


                $.getJSON('Services/ArtistFound.aspx?' + escape($(this).val()), function (results) {

                    if (results.available) {
                        if (nameFoundMessage.is(':visible')) {
                            nameFoundMessage.html('The name was found');
                        }
                    }
                    else {

                        nameFoundMessage.show();
                        nameFoundMessage.html('The name was not found');
                    }
                });

            }
        });
    });
</script>

The page has an input field with an id of "name" and when I blur off of that it goes into a service folder which has another aspx page ArtistFound.aspx and in that Page load, I have the following:

        Response.ContentType = "application/json";

        string name = Request.QueryString.ToString();
        string output = string.Empty;

        name = db.Names.Single(x => x.Name== name).Name;

        if(name == null)
       开发者_Python百科 {
            output = "{available:false}";
        }
        else
        {
            output = "{available:true}";
        }

        Response.Write(output);
}

When I run the page and blur off the input, it says the following:

Failed to load resource: the server responded with a status of 500 (Internal Server Error)

I have tried ../Services/ArtistFound.aspx... and /Services/ArtistFound.aspx..., but it still gives me the same error.


You want:

    name = db.Names.FirstOrDefault(x => x.Name== name);

    if(name != null && name.Name != null)
    {
        output = "{available:true}";
    }
    else 
    {
        output = "{available:false}";
    }

This will return null if it is not found rather than throwing an exception like Single() does.

I would also recommend you use an ASHX handler rather than an ASPX page to do this call. To do this you just add a 'Generic Handler' file in visual studio then you can put replace the ProcessRequest method with this:

    public void ProcessRequest(HttpContext context)
    {
        string name = context.Request.QueryString.ToString();
        string output = string.Empty;

        name = db.Names.FirstOrDefault(x => x.Name == name);

        if (name != null && name.Name != null)
        {
            output = "{available:true}";
        }
        else
        {
            output = "{available:false}";
        }

        context.Response.ContentType = "application/json";
        context.Response.Write(output);
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜