.ajax (JQuery) 到我拥有的域的跨域问题 -- 简单的 PHP 页面

发布于 2024-12-25 05:42:47 字数 791 浏览 0 评论 0原文

所以我知道这是一个常见问题,并且看到很多人在谈论它,但觉得我的情况很独特,可能不像其他人那么复杂。

我有一个主机网站,并尝试使用 JQ 和 PhoneGap 构建 iPhone 应用程序。

我希望人们能够从应用程序将他们的分数传递到我的主域,但我遇到了可怕的情况: “Access-Control-Allow-Origin 不允许 Origin null。” 当我尝试调用此命令时:

$.ajax({
        type: "POST",
        url: 'http://www.homesite.com/thephppage.php',
        data: {
            'guid': '12333-54',
            'score': 52,
            'initials': 'tod'
        },
        success: function (data) {
            try {

                }
                else {

                }
            }
            catch (err) {
                alert(err);
            }
        },
        error: function (xhr) {
            alert(xhr.responseText);
        }
    });

由于这是调用我拥有的域,因此我可以做一些简单的事情来纠正此问题吗?

谢谢。 时间

So I know this is a common problem and have seen a lot of people talking about it but feel that my situation is unique and maybe not as involved as others.

I have a host website and trying to build an iPhone app with JQ and PhoneGap.

I want people to be able to pass their score to my home domain from the app but am getting the dreaded:
"Origin null is not allowed by Access-Control-Allow-Origin."
when I try and call this:

$.ajax({
        type: "POST",
        url: 'http://www.homesite.com/thephppage.php',
        data: {
            'guid': '12333-54',
            'score': 52,
            'initials': 'tod'
        },
        success: function (data) {
            try {

                }
                else {

                }
            }
            catch (err) {
                alert(err);
            }
        },
        error: function (xhr) {
            alert(xhr.responseText);
        }
    });

Since this is calling out to a domain I own, is there something simple I can do to rectify this issue?

Thanks.
T

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

╰つ倒转 2025-01-01 05:42:47

您拥有两个域的事实并不会改变 ajax 请求不能跨域的事实。

由于这是调用我拥有的域,我可以采取一些简单的措施来纠正此问题吗?

看看设置CORS,它应该允许您发出这些跨域请求。另外,根据 jQuery 文档,jQuery 应该支持 CORS 请求——主要是

xhrFields(1.5.1 添加) Map 要设置的 fieldName-fieldValue 对的映射
在本机 XHR 对象上。例如,您可以使用它来设置
如果需要,跨域请求的 withCredentials 设置为 true。

$.ajax({ url: a_cross_domain_url, xhrFields: {
withCredentials: true } });在 jQuery 1.5 中,withCredentials 属性未传播到本机 XHR,因此
要求它的 CORS 请求将忽略此标志。为此,我们
如果您需要使用 jQuery 1.5.1+,建议使用它。


目前,由于 Firefox 中的一个错误,.getAllResponseHeaders()
尽管 .getResponseHeader('Content-Type') 返回空字符串
返回非空字符串,自动解码 JSON CORS 响应
在 Firefox 中不支持 jQuery。

That fact that you own both domains doesn't change the fact that ajax requests cannot be cross domain.

Since this is calling out to a domain I own, is there something simple I can do to rectify this issue?

Yes

Have a look at setting up CORS, which should allow you to make these cross-domain requests. Also, according to the jQuery docs, jQuery should support CORS requests—mostly

xhrFields (added 1.5.1) Map A map of fieldName-fieldValue pairs to set
on the native XHR object. For example, you can use it to set
withCredentials to true for cross-domain requests if needed.

$.ajax({ url: a_cross_domain_url, xhrFields: {
withCredentials: true } }); In jQuery 1.5, the withCredentials property was not propagated to the native XHR and thus
CORS requests requiring it would ignore this flag. For this reason, we
recommend using jQuery 1.5.1+ should you require the use of it.


At present, due to a bug in Firefox where .getAllResponseHeaders()
returns the empty string although .getResponseHeader('Content-Type')
returns a non-empty string, automatically decoding JSON CORS responses
in Firefox with jQuery is not supported.

深爱不及久伴 2025-01-01 05:42:47

您必须将 crossDomain 更改为 true

检查 jquery ajax api 和选项
http://jqapi.com/#p=jQuery.ajax

you will have to change the crossDomain to true.

check the jquery ajax api and options
http://jqapi.com/#p=jQuery.ajax

入怼 2025-01-01 05:42:47

为了避免从应用程序调用不同的域,您可以在主机网站上创建一个页面,将分数注册转发到您的主域。然后您可以在主机网站上调用此页面。

您可以使用 PHP 使用 HttpRequest::send

例如(不包括用户的身份验证):

$url = 'http://mydomain.com/score.php';
$r = new HttpRequest($url, HttpRequest::METH_GET);
$r->addQueryData(array('initials' => $initials, 'score' => $score));

try {
    $json = $r->send()->getBody();
    // output the response to forward it to the app
    echo $json;
} catch (HttpException $ex) {
    // handle error
}

To avoid calling a different domain from the app you can make a page on your host website which forwards the score registration to your home domain. You can then call this page on the host website.

You can use PHP to forward the data using HttpRequest::send

For example (not including authentication of the user):

$url = 'http://mydomain.com/score.php';
$r = new HttpRequest($url, HttpRequest::METH_GET);
$r->addQueryData(array('initials' => $initials, 'score' => $score));

try {
    $json = $r->send()->getBody();
    // output the response to forward it to the app
    echo $json;
} catch (HttpException $ex) {
    // handle error
}
痴骨ら 2025-01-01 05:42:47

在职的!!!噢,荣耀!!! (有点):这就是我所做的...

而不是使用 .ajax,我采用了 JSONP 路线(有点)并动态地向我的头部添加了一个标签,如下所示:

var head = document.getElementsByTagName('head')[0];
  script = document.createElement('script');
  script.type = 'text/javascript';
  script.src = 'http://thesite.co/thepage.php?var1=123&var2=432&var3='ttt';
  head.appendChild(script);

我什至不必给它一个 CALLBACK 方法,因为(因为我拥有目标站点并且知道它的到来)在我的 PHP 端,我用这样的 methodName 包装返回:

$encoded = json_encode($json);
echo "testMethod(" . $encoded . ")";
除了在我该死的 iPhone 和 iPad 模拟器中之外,这一切都非常有效! (天哪,我需要购买真正的设备...)所以我仍然不知道这是否适用于实际设备,但它现在可以在 Chrome 和 Safari 中使用...希望我能弄清楚如何让它在该手机上工作!

感谢大家的帮助!

==========第二个更好的移动解决方案====================== 这比 JSONP - 动态脚本解决方案效果更好

......您的头下您的 Phonegap 和 JQ 呼叫插入此标签。

<script type="text/javascript">
        $(document).bind("mobileinit", function () {
           $.mobile.allowCrossDomainPages = true;
        });
    </script>

然后在 XCODE 资源文件夹中的 Phonegap.plist 文件中,将域添加到外部域...即。电话间隙.com。 (省略 http 或 www)。

WORKING!!! OH GLORY!!! (sort of): Here's what I did...

Instead of use the .ajax, I went the JSONP route (sort of) and added a tag to my head dynamically like so:

var head = document.getElementsByTagName('head')[0];
  script = document.createElement('script');
  script.type = 'text/javascript';
  script.src = 'http://thesite.co/thepage.php?var1=123&var2=432&var3='ttt';
  head.appendChild(script);

I didnt even have to give it a CALLBACK method because (since I own the target site and know its coming) on my PHP side, I wrap the return with a methodName like this:

$encoded = json_encode($json);
echo "testMethod(" . $encoded . ")";
This worked marvelously EXCEPT IN MY DARN iPhone and iPad simulators!!! (gosh I need to buy the real devices...) So I STILL dont know if this works on the actual devices but it works now in Chrome AND Safari... lets hope I can figure out how to make it work on that phone!

THANKS to everyone for their help!

==========SECOND BETTER MOBILE SOLUTION====================== This works better than the JSONP - dynamic Script solution...

In your head under your Phonegap and JQ calls insert this tag.

<script type="text/javascript">
        $(document).bind("mobileinit", function () {
           $.mobile.allowCrossDomainPages = true;
        });
    </script>

Then in your Phonegap.plist file in your XCODE Resources folder, add the domain to External Domains... ie. phonegap.com. (Leave off http or www).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文