jQuery.ajax() cross-domain JSONP via POST
Hi there,
I probably should have originally addressed this to the dev list:
[ http://groups.google.com/group/jquery-en/browse_thread/thread/8bd0e249e2041b3b
]; but if we can churn away on this here, I'll update that post as
necessary.
I've spotted what may be a bug in the jQuery.ajax() code, but I wanted
to touch base here to verify that I am not missing something.
I am attempting to POST some JSON data across domains via jQuery's low-
level .ajax() call; since it is cross-domain, I use the JSONP
dataType. Here's the options for my call:
options = {
type: 'POST',
url: query_url,
dataType: 'jsonp',
data: JSON.stringify(query),
processData: false,
contentType: 'application/json',
success: that.processResponse,
error: that.processError,
};
jQuery.ajax(options);
The problem occurs when the jQuery.ajax() code attempts to insure that
a callback function placeholder is available in the data to enable the
round-trip JSONP protocol. I am handing the .ajax() function a JSON
string in the data element, but there is no code in the .ajax()
function which handles that situation.
Here's the regular expression which looks for the HTTP query parameter
style syntax "=?" (1.2.6 line 2587):
var jsonp, jsre = /=\?(&|$)/g, status, data,
Here's the relevant code (1.2.6 lines 2594-2602):
// Handle JSONP Parameter Callbacks
if ( s.dataType == "jsonp" ) {
if ( type == "GET" ) {
if ( !s.url.match(jsre) )
s.url += (s.url.match(/\?/) ? "&" : "?") + (s.jsonp ||
"callback") + "=?";
} else if ( !s.data || !s.data.match(jsre) )
s.data = (s.data ? s.data + "&" : "") + (s.jsonp || "callback") +
"=?";
s.dataType = "json";
}
Since this code falls through the "GET" and then encounters data but
no match, it appends the callback function name to the JSON string,
resulting in POST data that looks like this:
{"api_key":"blahblahblah"}&callback=jsonp1217951088150
This blows up the JSON parser on the remote server.
I am fairly certain this works ok if the callback function parameter &
name could be (re)placed in the JSON string. POSTing to the remote
server works OK when I make a regular JSON POST with the callback
included as a parameter in data (and then blows up when the response
is automatically parsed as JSON data rather than JSONP).
Please let me know if I am misinterpreting our ability to POST data
across domains, abusing the jQuery.ajax() call somehow, or otherwise
smoking crack.
Thanks,
gf