Ajax jquery请求到另一个域


Ajax jquery request to another domain

我有一个php文件名为paste。php在服务器的目录下域名是example.com (http://www.example.com/ajax/paste.php)php文件如下所示:

<?php
$id=($_GET['create']);
$paste=($_GET['paste']);
$toly=($_GET['toly']);
if($id=='create'){
echo "hello";}
else{
echo "world";
} ?>

在另一个服务器与不同的域我有一个简单的html文件(www.example/demo/index.html)我正试图使一个ajax调用上面的php文件没有运气我的jquery看起来像:

var url="http://www.example.com/ajax/paste.php";
s="create=create&paste=hello&toly=this";
$.ajax({
   type: "GET",
    xhrFields: {
      withCredentials: true
   },
   url: url,
   data: s,
   success: function(msg){
   alert(msg);
   },error:function (jqXHR){
                    alert(jqXHR.status.error);
                }  
 }); 

我做错了什么?

EDIT:忘记xhr,我只是想得到我作为响应的字符串有办法吗?

从JavaScript中可以动态地在文档的头部创建一个新元素。当您这样做时,浏览器可以从您指定的任何域请求数据。如果被调用的代码包含某个函数的执行,那么该函数将能够链接到您的代码。下面是示例:

    var head = document.getElementsByTagName("head")[0];
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = url;
    head.appendChild(script);

您还需要在脚本中定义一个函数:

    function success(abc){
        alert('Yey'+abc);
    }

另一个域的脚本应该是这样的:

    success('some_data_here');

该数据也可以是JSON。当JSON与这样的函数调用结合在一起时,它被称为JSONP。

往下读:

http://en.wikipedia.org/wiki/JSONP

除非进行跨域资源共享,否则无法实现跨域XHR。同源策略阻止您。

您可以使用服务器端代理或编写您的服务来支持JSONP。

http://devlog.info/2010/03/10/cross-domain-ajax/

编辑:哦,是的,看看这条评论。查看其他线程