如何在jquery中调用外部URL?

32 ajax jquery cross-domain-policy

我想用jquery在Facebook墙上发表评论.

但我的ajax电话没有外部网址.

任何人都可以解释我们如何使用外部URL与jquery?

下面是我的代码:

var fbUrl="https://graph.facebook.com/16453004404_481759124404/comments?access_token=my_token";

$.ajax({        
    url: fbURL ,
    data: "message="+commentdata,
    type: 'POST',
    success: function (resp) {
        alert(resp);
    },
    error: function(e){
        alert('Error: '+e);
    }  
});
Run Code Online (Sandbox Code Playgroud)

它给出了xmlhtttprequest错误.

Ben*_*ard 28

所有这些答案都是错误的!

就像我在评论中说的那样,你因为URL失败了" 同源策略 "而得到错误的原因,但你仍然可以使用AJAX函数来打击另一个域,看看Nick Cravers对这个类似问题的回答:

您需要通过添加&callback =?来触发$ .getJSON()的JSONP行为?在查询字符串上,像这样:

$.getJSON("http://en.wikipedia.org/w/api.php?action=query&prop=revisions&rvprop=content&titles="+title+"&format=json&callback=?",
function(data) {
    doSomethingWith(data); 
}); 
Run Code Online (Sandbox Code Playgroud)

你可以在这里测试一下.

如果不使用JSONP,您就会遇到阻止XmlHttpRequest获取任何数据的同源策略.

考虑到这一点,以下代码应该工作:

var fbURL="https://graph.facebook.com/16453004404_481759124404/comments?access_token=my_token";

$.ajax({
    url: fbURL+"&callback=?",
    data: "message="+commentdata,
    type: 'POST',
    success: function (resp) {
        alert(resp);
    },
    error: function(e) {
        alert('Error: '+e);
    }  
});
Run Code Online (Sandbox Code Playgroud)


Fer*_*ndo 7

JQuery和PHP

在PHP文件"contenido.php"中:

<?php
$mURL = $_GET['url'];

echo file_get_contents($mURL);
?>
Run Code Online (Sandbox Code Playgroud)

在html中:

<script type="text/javascript" src="js/jquery/jquery.min.js"></script>
<script type="text/javascript">
    function getContent(pUrl, pDivDestino){
        var mDivDestino = $('#'+pDivDestino);

        $.ajax({
            type : 'GET',
            url : 'contenido.php',
            dataType : 'html',
            data: {
                url : pUrl
            },
            success : function(data){                                               
                mDivDestino.html(data);
            }   
        });
    }
</script>

<a href="#" onclick="javascript:getContent('http://www.google.com/', 'contenido')">Get Google</a>
<div id="contenido"></div>
Run Code Online (Sandbox Code Playgroud)