AJAX跨网域请求 [英] AJAX cross domain request

查看:736
本文介绍了AJAX跨网域请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的主网域上有我的JavaScript档案,而我想从子网域拨打一些电话。

I have my JavaScript files on my main domain and I want to do some calls from the subdomain.

我已经添加:

url: "http://domain.com/ajax.php"

因此,完整代码是:

    $.ajax({
        type: "POST",
        url: "http://domain.com/ajax.php",
        data: {
            var1: var1,
            var2: var2
        },
        success: function(data){

        }
    });

但是在Firebug上,它会将请求显示为红色

But on Firebug it shows the request as red and it fails to respond. Also the POST parameters are there as they should.

我应该在子域上创建一个新的JS文件,并添加必要的代码,然后从那里AJAX调用?

Should I create a new JS file on the subdomain and add the necessary codes and do from there the AJAX calls?

EDIT:使用JSONP代码

> localhost / ajax.php (我从 sub.localhost

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);
        },
    });

,ajax.php包含:

and the ajax.php contains:

<?php
echo $_GET["id"];
?>


推荐答案

您可以使用

You can use Access-Control-Allow-Origin header to enable cross-domain requests.

阅读这里:跨源资源共享(CORS)

这篇关于AJAX跨网域请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆