سؤال

I have a local version of a JSONP response saved as a file so I can test my single-page web app from the local filesystem when I don't have an Internet connection.

It works fine when I load it directly from a <script> tag, but not when I try to load it with jQuery $.ajax() function. (Yes I have loaded jQuery successfully also from the local filesystem.)

I think it could be that jQuery always adds a callback parameter to the URL, and this doesn't make sense when the JSONP is coming from a statically named file rather than from the Internet.

I've tried passing jsonpCallback set to null or to the empty string '', but it makes no difference.

There are other oddities:

  • It works fine from jQuery when I pass the full path as the URL but fails when I use a relative URL, even though both work equally well when directly using a <script> tag.
  • When it fails, Google Chrome's developer tools network tab tells me the method was OPTIONS instead of GET! Using an absolute URL or the <script> tag method with either relative or absolute URL tells me the method is GET as expected.

Is this a known correct behaviour? A known incorrect behaviour?

Is something odd with jQuery or with Google Chrome? (I'm running in Windows 7 32 bit, Chrome version 21.)

هل كانت مفيدة؟

المحلول

While this might not solve all of my problems, it answers the specific problem posed in the question title:

This seems to be what I was missing:

JSONP request with jQuery that doesn't append a “callback” parameter?

jQuery.ajax() takes a settings object parameter. One of these settings is called jsonp. From the documentation:

As of jQuery 1.5, setting the jsonp option to false prevents jQuery from adding the "?callback" string to the URL or attempting to use "=?" for transformation. In this case, you should also explicitly set the jsonpCallback setting. For example, { jsonp: false, jsonpCallback: "callbackName" }

My code is now working with the current versions of Chrome (21), Firefox (13), Internet Explorer (9), Opera (12), and Safari (5) under Windows 7 (32 bit).

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top