2013-04-23 20 views
6

Sto provando a sparare a XMLHttpRequest su mongoDB per recuperare un documento tramite AJAX.REST Richiesta AJAX a mongoDB

Questo è il mio codice:

function getJsonDocumentByModeldid(model_id) { 
    var valoreInput = document.getElementById('inputModelId').value; 
    alert(valoreInput); 

    $.ajax({ 
     url: "http://localhost:28017/test/", 
     type: "get", 
     //data: "filter_a=" + valoreInput, 
     dataType: 'jsonp', 
     crossDomain: true, 

     success: function (data) { 
     alert("success"); 
     //var json2javascript = $.parseJSON(data); 
     manageLayout(); 
     }, 

     error: function (XMLHttpRequest, textStatus, errorThrown) { 
     alert("Status: " + textStatus + " Error:" + errorThrown); 
     } 
    }); 
} 

mia funzione restituisce sempre un errore. Quindi qual'è il problema?

+1

Qual è l'errore? – andyb

+0

la richiesta ajax fallisce con lo script, invece se copio url nel browser, la risposta del server con successo. non so qual è il problema ... – ilamaiolo

+0

L'errore di avviso è Jqueryxxxxxx non è stato chiamato! – ilamaiolo

risposta

6

Questa funzionalità è supportata come parte della Simple (read-only) REST Interface ma per rendere di dominio croce chiede alla --jsonp altrimenti saranno soggetti al problema Same origin policy, dal momento che l'indirizzo IP e la porta che si stanno facendo la richiesta non corrispondono l'indirizzo IP e porta su cui è in esecuzione mongoDB.

Inizio mongoDB con mongod.exe --rest --jsonp (più eventuali altre opzioni che si possono avere).

La seguente pagina di esempio può essere servita tramite un server Web (ad esempio Apache HTTP Server) o semplicemente salvata localmente e caricata nel browser come file . La richiesta è per informazioni su un dbCollection chiamato andyb, che ho creato in MongoDB prima con:

db.createCollection('andyb'); 

HTML

<!DOCTYPE html> 
<html> 
<head> 
    <meta http-equiv="content-type" content="text/html; charset=UTF-8"> 
    <title>mongoDB AJAX demo</title> 
    <script type='text/javascript' src='http://code.jquery.com/jquery-1.9.1.js'></script> 
    <script type='text/javascript'>//<![CDATA[ 
    $(function(){ 
    $.ajax({ 
     url: 'http://localhost:28017/local/andyb', 
     type: 'get', 
     dataType: 'jsonp', 
     jsonp: 'jsonp', // mongod is expecting the parameter name to be called "jsonp" 
     success: function (data) { 
     console.log('success', data); 
     }, 
     error: function (XMLHttpRequest, textStatus, errorThrown) { 
     console.log('error', errorThrown); 
     } 
    }); 
    });//]]> 
    </script> 
</head> 
<body> 
</body> 
</html> 

Molti browser supportano CORS ora che è un'alternativa (più moderno) modo per facilitare le risorse del dominio incrociato.

+0

Grazie mille per la tua risposta! – ilamaiolo

0

La risposta precedente può essere modificato utilizzando gli oggetti sospesi (vedi questa buona guida: "How do I return the response from an asynchronous call?):

<!doctype html> 
<meta charset="utf-8"> 
<title>mongoDB AJAX demo</title> 
<script src="http://code.jquery.com/jquery-latest.min.js" ></script> 
<script>  
    $(function(){ 
    // add rest = true and jsonp = true to /etc/mongodb.conf, 
    // then restart mongodb 
     $.ajax({ 
       url: "http://localhost:28017/local/startup_log/", 
       type: 'get', 
       dataType: 'jsonp', 
       jsonp: 'jsonp', // mongodb is expecting that                      
      }) 
      .done(function(data) { 
       d=JSON.stringify(data,undefined,1); 
       $("code").text(d).css("color","green"); 
      }) 
      .fail(function(request,status,error) { 
       $("code").text("get failed: "+error).css("color","red"); 
      }) 
      .always(function() { 
       console.log("finished") 
      }) 

    }); 
</script> 
<body> 
    <pre> 
    <code> 
    </code> 
    </pre> 

Comunque, in entrambi i casi il trattamento error: e fail() funziona solo se una porta non è prevista . Ad esempio:

url:"localhost/asdasdasd" 

determina un gestione degli errori, mentre

url:"localhost:28017/asdasdasd" 

risultati in un registro 404 nella console, come questo:

GET http://localhost:28017/?jsonp=jQuery110207253803350031376_1383522587177&_=1383522587178 404 (OK)