Ajax在不同的服务器上调用

时间:2013-04-08 05:38:08

标签: php ajax

我使用下面提到的脚本在不同的服务器上发送ajax call

$(document).ready(function() {
var uniqcod=$(".piczhu-widget").attr('id'); 

    $.ajax({
        url:'File Path...',
        type:'post',
        data:{uniId:uniqcod},
        success: function(result){
            $('.abcClass').html(result);
            }
        });
    });

脚本未收到任何回复。此脚本在同一台服务器上正常运行。是否有其他参数可用于在不同服务器上发送呼叫?

4 个答案:

答案 0 :(得分:1)

这应该使用JSONP解决问题:

$.ajax({
    url:'File Path...',
    type:'post',
    data:{uniId:uniqcod},
    dataType: 'jsonp', // use JSONP
    success: function(result){
        $('.abcClass').html(result);
        }
    });
});

答案 1 :(得分:1)

这是因为跨域策略。这是安全的事情。我建议您将该请求发送到位于您的服务器(您的域)上的cURL的PHP​​文件。

但您需要在服务器上安装cURL:http://curl.haxx.se/ 如果您使用的是基于Debian的服务器,您可以通过以下方式完成:sudo apt-get install php5-curl

示例:

<?php
$data = $_POST['data'];

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "URL FOR REQUEST");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");                                                                     
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);    
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);                                                                                                                                                                           

$result = curl_exec($ch);

echo $result;

?>

答案 2 :(得分:0)

你需要使用jsonp或cors来进行跨域ajax。下面给出的代码是cors的一个例子

示例代码:

jQuery.support.cors = true; 

function CrosDom_ajax(url) {
        if (window.XDomainRequest
        && $.browser.msie
        && $.browser.version < 10) {
        xdr = new XDomainRequest();
        if (xdr) {
            xdr.onload = function () {
               alert(xdr.responseText);

            };
            xdr.open("get", url);
            xdr.send();
        }
        }
        else {
            $.ajax({
                url: url,
                success: function (response) {


                },
                error: function (data) {
                }
            });
         }
    }

您还需要在服务器端编写以下代码,以允许跨域访问

Response.AppendHeader("Access-Control-Allow-Origin", "*");           

答案 3 :(得分:0)

最佳和可接受的方法是使用JSONP与不同的服务器通信。 JSONP是解决跨域脚本错误的绝佳选择。

阅读以下链接

What is JSONP all about?

jsonp with jquery

What are the differences between JSON and JSONP?

http://api.jquery.com/jQuery.getJSON/