Visualizzazione dei risultati da 1 a 7 su 7
  1. #1
    Utente di HTML.it
    Registrato dal
    May 2010
    Messaggi
    457

    Assegnare una variabile con JSON

    Salve ragazzi,
    mi trovo nella necessità di chiedervi un grande aiuto, praticamente dovrei invocare ajax con jquery e farmi restituire un json da assegnare ad una variabile javascript..esempio
    codice:
    function calcolaIndirizzi(){
    var indirizzi=$.Json("url?...",function(data){indirizzi= data});
    }
    Si puo' fare? Se si' come? Oppure come si potrebbe fare????

  2. #2
    Moderatore di Annunci siti web, Offro lavoro/collaborazione, Cerco lavoro L'avatar di cavicchiandrea
    Registrato dal
    Aug 2001
    Messaggi
    26,133
    Cavicchi Andrea
    Problemi con javascript, jquery, ajax clicca qui

  3. #3
    Utente di HTML.it L'avatar di carlomarx
    Registrato dal
    Oct 2009
    Messaggi
    1,669
    Se t'interessa io ti posso aiutare solo senza l'uso di jQuery… Se vuoi fare una lettura una tantum:

    codice:
    var miaVariabile;
    
    oXHR.onreadystatechange = function() {
    	if (oXHR.readyState === 4) { miaVariabile = JSON.parse(this.responseText); }
    };
    oXHR.open("GET", "mioFile.json", true);
    oXHR.send(null);
    Se invece vuoi crearti una funzione standard per leggere più file:

    codice:
    function loadFile (sURL, fCallback /*, argumentToPass1, argumentToPass2, etc. */) {
      var aPassArgs = Array.prototype.slice.call(arguments, 2), oXHR = new XMLHttpRequest();
      oXHR.onreadystatechange = function() {
        if (oXHR.readyState === 4) { fCallback.apply(oXHR, aPassArgs); }
      };
      oXHR.open("GET", sURL, true);
      oXHR.send(null);
    }
    
    var miaVariabile;
    
    loadFile("mioFile.json", function() { miaVariabile = JSON.parse(this.responseText); });

  4. #4
    Utente di HTML.it
    Registrato dal
    May 2010
    Messaggi
    457
    Ciao carlomarx,
    grazie per avermi dato una risposta,
    pero' io avrei bisogno per il mio progetto di utilizzare jquery.
    Ho visto sul sito ufficiale di jquery che esiste una funzione $.JSON che ritorna una stringa in formato json, ma non ho ben capito se dentro la callback si possa assegnare ad una variabile diciamo globale il valore ritornato.
    Quello che mi sono chiesto è seppure fosse possibile ottenere un comportamento simile

    var indirizzi=$.Json("url?...",function(data){return data});

    la chiamata è sincrona, nel senso che fino a quando non ottengo il return, l'secuzione del codice deve fermarsi e attendere il completamento dei dati....sarà possibile?

  5. #5
    Moderatore di Annunci siti web, Offro lavoro/collaborazione, Cerco lavoro L'avatar di cavicchiandrea
    Registrato dal
    Aug 2001
    Messaggi
    26,133
    Ma... non conosco questo invio (e non trovo riscontri su jquery) ma cosi hai provato
    $.Json("url?...",function(data){
    var indirizzi = data});
    la variabile indirizzi dovrebbe essere {nome:valore,nome:valore, etc...}
    Cavicchi Andrea
    Problemi con javascript, jquery, ajax clicca qui

  6. #6
    Utente di HTML.it
    Registrato dal
    May 2010
    Messaggi
    457
    ragazzi ho provato cosi' un po' seguendo il suggerimento del sito ufficiale

    codice:
    <html>
    
    
    <script src="/system/modules/it.minambiente.ambiente2010.template/resources/scripts/mappe_js/jquery.js"></script>
    
    
    <body>
    
    <h1>  Chiamata JSON </h1>
    <script>
    var globale;
    alert('QUERYYYYYY');
    var oggetto = $.getJSON("http://localhost/gaia/test_xml", function(data) {
      alert(' nomignolo == '+data.articolo );
      //this.globale=data;
         
     
    
    })
    //.error(function() { alert("error"); })
    
    //alert(' nomignoloneeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee == '+globale );
    
    alert(oggetto.articolo);
    
    </script>
    
    </body>
    
    </html>
    la variabile alert(oggetto.articolo); non viene stampata ....perchè? non è possibile allora assegnare ad una variabile il valore rtestituito da una chiamata json?

  7. #7
    Utente di HTML.it L'avatar di carlomarx
    Registrato dal
    Oct 2009
    Messaggi
    1,669
    Tu stai cercando di parsare in json un foglio XML! Se vuoi trasformare un xml in json devi fare qualcosa del genere:

    codice:
    function buildValue(sValue) {
    	if (/^\s*$/.test(sValue)) { return null; }
    	if (/^(true|false)$/i.test(sValue)) { return sValue.toLowerCase() === "true"; }
    	if (isFinite(sValue)) { return parseFloat(sValue); }
    	if (isFinite(Date.parse(sValue))) { return new Date(sValue); }
    	return sValue;
    }
    
    function getXMLData (oXMLParent) {
    	var vResult = /* true is the default value for empty nodes */ true, nLength = 0, sTxtContent = "";
    	if (oXMLParent.hasAttributes()) {
    		vResult = {};
    		for (nLength; nLength < oXMLParent.attributes.length; nLength++) {
    			iAttrib = oXMLParent.attributes.item(nLength);
    			vResult["@" + iAttrib.nodeName.toLowerCase()] = buildValue(iAttrib.nodeValue.replace(/^\s+|\s+$/g, ""));
    		}
    	}
    	if (oXMLParent.hasChildNodes()) {
    		var iKey, iValue, iXMLChild;
    		for (var iChildId = 0; iChildId < oXMLParent.childNodes.length; iChildId++) {
    			iXMLChild = oXMLParent.childNodes.item(iChildId);
    			if (iXMLChild.nodeType === 1 && !iXMLChild.prefix) {
    				if (nLength === 0) { vResult = {}; }
    				iKey = iXMLChild.nodeName.toLowerCase();
    				iValue = getXMLData(iXMLChild);
    				if (vResult.hasOwnProperty(iKey)) {
    					if (vResult[iKey].constructor !== Array) { vResult[iKey] = [vResult[iKey]]; }
    					vResult[iKey].push(iValue);
    				} else { vResult[iKey] = iValue; nLength++; }
    			} else if (iXMLChild.nodeType === 3) { sTxtContent += iXMLChild.nodeValue.replace(/^\s+|\s+$/g, ""); }
    			else if (iXMLChild.nodeType === 4) { sTxtContent += iXMLChild.nodeValue; }
    		}
    	}
    	if (nLength > 0) { vResult.keyValue = buildValue(sTxtContent); /* Object.freeze(vResult); */ }
    	else if (sTxtContent) { vResult = buildValue(sTxtContent); }
    
    	return vResult;
    }
    
    var miaVariabile;
    oXHR = new XMLHttpRequest();
    oXHR.onreadystatechange = function() { if (oXHR.readyState === 4) { miaVariabile = getXMLData(this.responseXML); } };
    oXHR.open("GET", "http://localhost/gaia/test_xml", true);
    oXHR.send(null);
    
    alert(JSON.stringify(miaVariabile));
    Prova con questo codice e vedi se è quello che vuoi. Poi per jQueryizzarlo ci si mette un attimo&hellip;

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2025 vBulletin Solutions, Inc. All rights reserved.