开发者

Internet Explorer $.ajax / MVC JSON call failing

开发者 https://www.devze.com 2023-01-10 17:23 出处:网络
I have a relatively simple example of an MVC page that is using jQuery to make a POST to get some JSON data and then just show a success/failure message when it is done. The code works perfectly fine

I have a relatively simple example of an MVC page that is using jQuery to make a POST to get some JSON data and then just show a success/failure message when it is done. The code works perfectly fine in the other browsers but in IE7/8 it seems to fail 4/5 times.

Here is the MVC View Page:

<asp:Content runat="server" ContentPlaceHolderID="MainContent">
    <p id="message"></p>
</asp:Content>

<asp:Content runat="server" ContentPlaceHolderID="HeadContent">
   <script type="text/javascript" src="<%= Url.Content("~/Scripts/jquery-1.4.1.min.js") %>"></script>

   <script type="text/javascript">
    $(document).ready(function () {
        $.ajax({
            type:"POST",
            url: "<%= Url.Action("GetData") %>开发者_如何学Go",
            data: "{}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(data){
                $("#message").html("success");
            },
            error: function(XMLHttpRequest, textStatus, errorThrown){
                $("#message").html("error: " + textStatus + "<br/>exception:" + errorThrown);
            }
        });
    });
    </script>
</asp:Content>

The controller is pretty simple as well:

[HttpPost]
public ActionResult GetData()
{
    IList<string> people = new List<string>
    {
        "A",
        "B",
        "C",
        "D",
        "E"
    };

    return Json(people);
}

It seems to fail in IE 4 out of every 5 times roughly. I put some logging code in the controller and it calls the controller action every time, even when it fails. Does anyone see anything that I am doing wrong here?

When it hits my error handler function the textStatus is just set to "error" and errorThrown is undefined.


Try with {} (or null) instead of "{}" as the data.

As you're sending JSON to the action (contentType is set to JSON), unless you have a JSON Value Provider Factory set up, this might be the cause of the problem.

Take a look at Phil Haack's article on Sending JSON to an ASP.NET MVC Action Method Argument if this is something you're keen to do.

0

精彩评论

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