Mr Shoubs
Mr Shoubs

Reputation: 15399

Why does this $.getJSON request error?

I have the following script that call a http handler. It calls the http handler, and in fiddler, I can see the JSON returned correctly, however this script always ends up in the error block. How can I determine what is wrong?

    <script type="text/javascript">
        function GetConfig() {
            $.getJSON("http://localhost:27249/Handlers/GetServiceMenuConfiguration.ashx", function(d) {
                alert("success");
            }).success(function(d) {
                alert("success");
            }).error(function(d) {
                alert("error");
            }).complete(function(d) {
                alert("complete");
            });
        }
    </script>

Upvotes: 0

Views: 1723

Answers (2)

BishopZ
BishopZ

Reputation: 6378

JQuery's built-in JSON parser is rather picky, even well formatted JSON can sometimes fail if the headers are not set perfectly. First try to do a $.ajax request with type:text property and log the response. This will differentiate between a connection problem and parse problem.

$.ajax({
  dataType:'text',
  url: '/Handlers/GetServiceMenuConfiguration.ashx',
  success: function(data) {
      console.log(data.responseText);
  }
});

If the problem is the connection, and you do need to request JSON across domains, then you could also use a library loader like LAB, yep/nope or Frame.js.

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1074335

I see that you're including the server name (localhost) and port (27249). Ajax requests are controlled by the Same Origin Policy, which forbids cross-origin requests in the normal case. (If you're not doing a cross-origin call, you don't need to include the http://localhost:27249 portion of your URL, which is what makes me think you might be doing one.)

You can do cross-origin calls if the browser supports them and if your server code handles the CORS requests properly. Alternately, you might look at using JSON-P.

Upvotes: 4

Related Questions