jQuery AJAX request doesn't evaluate script on other domain?
So, this question tells me that jQuery ajax requests don't insert script tags into the DOM, but jQuery evaluates them instead. I am loading some content into a div, and in that div I have some buttons courtesy of AddThis. The cod开发者_JS百科e for these buttons includes a script from http://s7.addthis.com. jQuery doesn't appear to be evaluating this script, I do not see my buttons. It happily evaluates another script from my own domain that is loaded in the same request.
Is there a way to tell jQuery to evaluate scripts from other domains, or is there a good reason for this behaviour which means I need to do this differently?
Thanks for reading.
jQuery's ajax
method abstracts a lot of the platform and use case specifics of making any type of asynchronous web request.
You can call the ajax
method with various combinations of parameters, and each time, a completely different workflow will be executed behind the scenes (synonyms for which include jQuery.get()
, jQuery.post()
, jQuery.getJSON()
, jQuery.getScript()
).
In the situations where you are making a request to a web page on the same domain as the current page, then jQuery will not utilize <script>
tags unless it is specifically told to (via setting the crossDomain
to true
). Instead, it will use the traditional method of AJAX; either the XMLHttpRequest Object
(and fall back to the various Microsoft implementations of ActiveX
).
However, in situations where you are making requests to different domains, it is not possible to use these methods because of the same origin policy in all modern browsers. In these circumstances, jQuery.ajax
will resort to using <script>
tags (the technique is named JSONP).
JSONP requires the response from the server to be formulated in a special way; namely valid JavaScript, which your response isn't. It's important to note that JSONP requires the cooperation of the server in this. For more information, read more in this question/answer, or on Wikipedia.
Your code is working on your domain because it's not required that the response from the server is valid JavaScript (which it isn't). However, when ajax() start's automatically using JSONP, your not meeting the valid JavaScript requirement.
精彩评论