AJAX cross domain request

☆樱花仙子☆ 提交于 2019-12-25 00:42:46

问题


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:

  1. Use document.domain on both sides.

  2. Use jsonP, either via jQuery 1.5's crossDomain ajax specification, or directly.



来源:https://stackoverflow.com/questions/6316915/ajax-cross-domain-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!