问题
I have my JavaScript files on my main domain and I want to do some calls from the subdomain.
I have added:
url: "http://domain.com/ajax.php"
So the full code is:
$.ajax({
type: "POST",
url: "http://domain.com/ajax.php",
data: {
var1: var1,
var2: var2
},
success: function(data){
}
});
But on Firebug it shows the request as red and it fails to respond. Also the POST parameters are there as they should.
Should I create a new JS file on the subdomain and add the necessary codes and do from there the AJAX calls?
EDIT: using JSONP code
I am using this on localhost/ajax.php
, which I call from sub.localhost
$.ajax({
dataType: 'jsonp',
data: 'id=10',
jsonp: 'jsonp_callback',
url: 'http://localhost/ajax.php',
success: function (data) {
console.log(data);
},
});
and the ajax.php contains:
<?php
echo $_GET["id"];
?>
回答1:
You can use Access-Control-Allow-Origin
header to enable cross-domain requests.
Read this: Cross-Origin Resource Sharing (CORS)
回答2:
Assuming you have jQuery 1.5+ you can use:
$.ajax({
crossDomain:true,
type: "POST",
url: "http://domain.com/ajax.php",
data: {
var1: var1,
var2: var2
},
success: function(data){
}
});
From the DOCS:
crossDomain(added 1.5)
Default: false for same-domain requests, true for cross-domain requests
If you wish to force a crossDomain request (such as JSONP) on the same domain, set the value of crossDomain to true. This allows, for example, server-side redirection to another domain
回答3:
For subdomain calls you have two options:
Use document.domain on both sides.
Use jsonP, either via jQuery 1.5's crossDomain ajax specification, or directly.
来源:https://stackoverflow.com/questions/6316915/ajax-cross-domain-request