-1

I have a static website, which I run on my local machine using jetty server (for testing) , and on github pages(live).

The source code is exactly same for both the sites. I used same browser (Mozilla Firefox) for below test I recently used the following code for a jQuery Ajax

 $.ajax({
        url: jsonFilePath,
        error: function (response) {... },
        success: function (responsedata) {
            var responsedata = JSON.parse(latestData);
            ...

The above code worked fine while running on my local server, but failed while running on github server (same browser)

It failed on github for this reason. It started working after defining dataType as below

 $.ajax({
            url: jsonFilePath,
            dataType: "json",
            ...

My Question here is, Why was this not caught during testing on local server? All the liberaries, data, json, js, jQuery files are same. What might have caused this difference in behaviour?

Community
  • 1
  • 1
Mohit Kanwar
  • 2,962
  • 7
  • 39
  • 59

1 Answers1

4

You haven't specified a dataType option in the object you pass to $.ajax. It therefore defaults to auto. This has two effects:

  1. It doesn't specify that JSON is prefered in the Accept request header. This makes no difference unless your server does content negotiation.
  2. It handles the response according to the Content-Type response header. This is what is tripping you up.

If the server supplies JSON and says, with the Content-Type, "This is JSON" then jQuery will parse it before passing the result to responsedata. This is what is happening on Github

If the server supplies JSON but says, with the Content-Type, "This is plain text" (i.e. if the server is misconfigured) then jQuery won't do that and you'll get a plain text string in responsedata. You'll get similar issues with other incorrect content-types.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • Exactly. The issue is that GitHub is correctly configured to deliver JSON with the correct MIME type, i.e., `application/json`, whereas your local server is not – jonny Mar 23 '16 at 10:50