Cómo llamar a url externas en jquery?


Estoy tratando de poner comentarios en el muro de Facebook usando jquery.

Pero mi llamada ajax no alowing url externa .

¿Puede alguien explicar cómo podemos usar url externas con jquery ?

A continuación está mi código:

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);
    }  
});

Está dando un error xmlhtttprequest.

Author: Ben Everard, 2011-01-06

7 answers

¡Todas estas respuestas son erróneas!

Como dije en mi comentario, la razón por la que está recibiendo ese error porque la URL falla en la " Política del mismo origen", pero todavía puede usarnos la función AJAX para golpear otro dominio, vea Nick Cravers responder a esta pregunta similar :

Necesita activar el comportamiento JSONP con $.getJSON () añadiendo & callback=? en el querystring, así:

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

Puedes probarlo aquí.

Sin usar JSONP estás golpeando el política del mismo origen que está bloqueando el XMLHttpRequest de obtener cualquier data de vuelta.

Con esto en mente, el siguiente código debería funcionar:

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);
    }  
});
 27
Author: Ben Everard,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:18:08

JQuery y PHP

En el archivo PHP " contenido.php":

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

echo file_get_contents($mURL);
?>

En 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>
 7
Author: Fernando,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-09-10 21:19:42

Es Cross-site scripting problema. Los navegadores modernos comunes no permiten enviar solicitudes a otra url.

 3
Author: Andrei Andrushkevich,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-01-06 09:20:33

Google la política de javascript mismo origen

En pocas palabras, la url que está tratando de usar debe tener la misma raíz y protocolo. tan http://yoursite.com no se puede acceder https://yoursite.com o http://anothersite.com

Es absolutamente NECESARIO omitir esta protección (que está a nivel del navegador, como señaló galimy), considere el módulo ProxyPass para su servidor web favorito.

 1
Author: ebaum,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-01-06 09:17:59

Creo que la única manera es mediante el uso de código PHP internel como MANOJ y Fernando sugieren.

Curl post / get in php file en su servidor call > llame a este archivo php con ajax

El archivo PHP digamos (fb.php):

$commentdata=$_GET['commentdata'];
$fbUrl="https://graph.facebook.com/16453004404_481759124404/comments?access_token=my_token";
curl_setopt($ch, CURLOPT_URL,$fbUrl);
curl_setopt($ch, CURLOPT_POST, 1);
// POST data here
curl_setopt($ch, CURLOPT_POSTFIELDS,
        "message=".$commentdata);

// receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$server_output = curl_exec ($ch);
echo $server_output;
curl_close ($ch);

Que utilizar AJAX LLEGAR a

fb.php?commentmeta=your comment goes here

Desde su servidor.

O haga esto con HTML y JavaScript simples desde el servidor externel:

Message: <input type="text" id="message">
<input type="submit" onclick='PostMessage()'>
<script>
function PostMessage() {
var comment = document.getElementById('message').value;
    window.location.assign('http://yourdomain.tld/fb.php?commentmeta='+comment)
}
</script>
 1
Author: Atanas Atanasov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-08 08:58:41

Hi url debe estar llamando a una función que a cambio dará respuesta

$.ajax({
url:'function to call url',
...
...

});

Intente usar / llamar al método API de facebook

 0
Author: lampdev,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-01-06 09:13:21

Siga los sencillos pasos a continuación podrá obtener el resultado

Paso 1 - Crea una función interna getDetailFromExternal en tu back-end. paso 2-En esa función llamar a la url externa mediante el uso de cUrl como abajo función

 function getDetailFromExternal($p1,$p2) {

        $url = "http://request url with parameters";
        $ch = curl_init();
        curl_setopt_array($ch, array(
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true            
        ));

        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        $output = curl_exec($ch);
        curl_close($ch);
        echo $output;
        exit;
    }

Paso 3 - Llama a esa función interna desde tu front end usando javascript/jquery Ajax.

 -1
Author: MANOJ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-05 05:33:49