开发者

Why in the world this ajax call is not working

开发者 https://www.devze.com 2023-02-09 21:31 出处:网络
$(function () { $(\'input#UserName\').blur(function () { var username = $(\'input#UserName\').val(); $.ajax(
$(function () {
    $('input#UserName').blur(function () {
        var username = $('input#UserName').val();
        $.ajax(
        {
            type: "POST",
            url: "Profile/CheckAvailability",
            data: "username=" + username,               
            success: function (result) {
                //Some code here
            },
            error: function () {
                alert("Sorry! We could not receive your feedback at this time.");                
            }
        });
    });
});

and the code on Profile controller

    [HttpPost]
    public JsonResult Chec开发者_Python百科kAvailability(string username)
    {
        bool isAvailable = false;
        //Some code here
        return Json(new {success = isAvailable});
    }

Each time alert("Sorry! We could not receive your feedback at this time."); is being triggered.

Thanks.


Here are a few tips:

  1. Make sure your controller action is not throwing an exception (especially the part where you say //Some code here). This could be verified by stepping through it and debugging.
  2. Make sure to always URL encode your request parameters and never use string concatenation:

    data: { username: username },
    
  3. Never hardocde urls in your javascript file. Always use Url helpers when dealing with urls (if this is a separate javascript then you could use a global js variable set in your view):

    url: '<%= Url.Action("Profile", "CheckAvailability") %>',
    
  4. Use FireBug to see what is being sent to and received from the server.


Try setting dataType as "json", because the one you specified isn't valid. Valid dataTypes from jquery documentation: xml, json, jsonp, html, text.

Check out this url about ajax error handling: jQuery Ajax error handling, show custom exception messages

0

精彩评论

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