繁体   English   中英

Ajax在不同的服务器上调用

[英]Ajax call on different server

我正在使用下面提到的脚本在不同的服务器上发送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);
            }
        });
    });

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

这应该使用JSONP解决问题:

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

这是因为跨域策略。 这是安全的事情。 我建议您将该请求发送到位于您的服务器(您的域)上的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;

?>

你需要使用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", "*");           

最好的和接受的方法是使用JSONP与不同的服务器通信。 JSONP是一个很好的解决跨域脚本错误的方法。

阅读以下链接

什么是JSONP?

jsonp与jquery

JSON和JSONP有什么区别?

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM