我在site1.com上有一个返回HTML的php脚本。假设为http://site1.com/script.php 并返回:
<div id="test"><img src="path"/></div>
我想在site2.com上接收并显示该HTML。
AJAX. jQuery:
$.ajaxSetup({
crossDomain: true,
dataType: "jsonp text html" //like documentation said
});
$.get("http://site1.com/script.php", { param: param}, function(data) {$("#some_id").html(data);})
但收到了错误消息:
Uncaught SyntaxError: Unexpected token < in http://site1.com/script.php line 1
我尝试了很多dataTypes,都没用,我也无法在site2.com上使用任何php脚本。如何才能使它起作用?
You tell jquery to treat data like json. Just delete
dataType: "jsonp text html" //like documentation said
and should be okay. You have to tell jquery to treat returned data as a html code, not json object.
From the documentation:
`dataType` String
Default: Intelligent Guess (xml, json, script, or html)
"jsonp text html"
is not "xml, json, script, or html"
If you want to get cross-domain data without using CORS, then you have to use JSONP.
If you use JSONP, then the data you are fetching must be expressed in JSONP (which consists of a JavaScript program consisting of a single function call with one argument that is either an object or an array) and not plain HTML.
You are getting an error because you are trying to execute an HTML document as if it was JavaScript.
This stuff will ONLY work in case this script runs on "site1.com".
If that's not the case, your one and only alternative is using JSON-P. JQuery has built-in support for JSON-P and jQuery will use it automatically when you call $.getJSON() and paste "?callback=?" to the URL to call.
JSONP stands for "JSON with padding." The padding here is a function call: JSONP passes JSON data from one domain as a parameter to a callback function that can then be executed as a script at another domain. You should set up the PHP script at site1.com so it accommodates a callback in the query string -- that is, a GET request for http://site1.com/script.php?callback=foo should return:
foo (
{ 'add_me' : '<div id="test"><img src="path"/></div>' }
)
. Then you can use jQuery's $.get() in a script at site2.com like so:
$.get('http://site1.com/script.php', function(data) {
$(body).prepend(data['add_me']);
alert('Load was performed.');
});
Right now, the browser's trying to execute <div id="test"><img src="path"/></div>
(or whatever) as a script and chokes on the '<'.
Read more about the same-origin policy (SOP) that's complicating your life: http://en.wikipedia.org/wiki/Same_origin_policy . Learn about JSONP: http://www.ibm.com/developerworks/library/wa-aj-jsonp1/ . Learn some SOP workarounds: http://www.ibm.com/developerworks/web/library/wa-crossdomaincomm/index.html?ca=drs- . Implement a more modern, less cumbersome solution than the one I describe above: http://hacks.mozilla.org/2009/07/cross-site-xmlhttprequest-with-cors/ .