Unable to get response using Jquery.getJSON with m

2019-04-12 15:10发布

问题:

I'm trying to get a jSON response using jQuery 1.5.1 with mvc3 and the javascript is silently crashing out. Debugging the server side code i'm definitely passing a populated list to the response.

Some further information in regards to the comments.

The response returned in firebug is thus:

[{"LocationId":"ASXX0413","LocationName":"Albany, Australia"}]

and firebug also recognises it as a jSON object.

My Javascript:

 weatherEvents: function () {

        jQuery("a#getweather").click(function (event) {

            event.preventDefault;
            var query = jQuery("#Farm_Weather").val();

            if (query === "") {
                return;
            }

            jQuery.getJSON("/Farm/Weather", { location: query }, function (data) {
                var items = [];

                jQuery.each(data, function (key, val) {
                    items.push("<li>" + val.LocationId + " : " + val.LocationName + "</li>");
                });

                jQuery("<ul/>", {
                    "class": "weather-location-list",
                    html: items.join("")
                }).appendTo("div.weatherdiv");
            });
        });
    }

My server side code:

    [HttpGet]
    public JsonResult Weather(string location)
    {
        string requestUrl = string.Format(
            "http://xoap.weather.com/search/search?where={0}",
            HttpUtility.UrlEncode(location.Trim()));

        XmlDocument xmlDoc = new XmlDocument();
        XmlNodeList nodeList = null;

        // Place a call to Weather.com and search for this location
        xmlDoc.Load(requestUrl);
        nodeList = xmlDoc.SelectNodes("/search/loc");

        // Cast our nodelist and get a new anonymous type.
        var jsonWeather = nodeList.Cast<XmlElement>()
                                  .Select(x => new
                                  {
                                      LocationId = x.GetAttribute("id"),
                                      LocationName = x.InnerText
                                  });

        return Json(jsonWeather.ToList(), JsonRequestBehavior.AllowGet);
    }

回答1:

The answer it turns out it quite simple.....

There is a known bug with jQuery 1.5.1 and the jquery.validate plugin shipped with mvc.

further info can be found here and the updated plugin can be found here.



回答2:

By your code it seems like u r making some tree structure with Ul li and appending it too a div with the json that you are getting .

you can make a ajax request and return the json object as a string.

Some sample code for U.

ViewData["JsonStr"] = JsonConvert.SerializeObject(objTree);

//here objTree is my composite that i want to to serialize and interpret it on client side.

objOS = Sys.Serialization.JavaScriptSerializer.deserialize(jsonData)

its a work around that can help you out.