Minha chamada de Ajax não está retornando nada, mas também não está falhando
-
21-09-2019 - |
Pergunta
Eu tenho este html:
<input type="text" id="text"/>
<input type="button" id="submit" value="Submit" />
<div id="twitter_update_list">
</div>
E este JavaScript:
var xmlHttp;
document.body.onclick = function(){
var username = document.getElementById('text').value;
selectUser(username);
}
function selectUser(username){
var url = "http://twitter.com/statuses/user_timeline/" + username + ".json?callback=twitterCallback2&count=100";
try{// Opera 8.0+, Firefox, Safari
xmlHttp = new XMLHttpRequest();
}catch (e){// IE
try{
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
xmlHttp.onreadystatechange = processRequest;
xmlHttp.open( "GET", url, true );
xmlHttp.send( null );
}
function processRequest(){
if ((xmlHttp.readyState == 4) && (xmlHttp.status == 200)) {
if ( xmlHttp.responseText == "Not found" ) {
document.getElementById('twitter_update_list').innerHtml = "Not found";
}else if(xmlHttp.responseText == " "){
document.getElementById('twitter_update_list').value = "Empty";
}else{
// No parsing necessary with JSON!
document.getElementById('twitter_update_list').value = xmlHttp.responseText;
console.log(xmlHttp.responseText);
}
}
}
Estou olhando para o Firebug e vejo tudo isso é enviado corretamente, mas não recebo nenhuma resposta. Ah, e estou usando JavaScript bruto porque quero praticá -lo. =)
Solução
Você está tentando fazer o domínio cruzado xmlHttPrequest. Não funciona, embora o serviço possa estar apoiando o JSONP. Para fazer um pedido de JSOP, você precisa injetar um <script>
Tag com os manipuladores de eventos corretos ou use uma estrutura como o jQuery.
Outras dicas
Se você usar o jQuery, você pode fazer isso simples
$.load("http://twitter.com/statuses/user_timeline/"+username,
function(data)
{
alert(data);
}
);
que imprimirá a linha de usuário do nome de usuário fornecido
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow