¿Cómo puedo consumir un documento JSON sin jQuery? En lugar de llamar al método getJSON()
, me gustaría diseñar el mío. ¿Cómo puedo hacer eso?Consumir datos JSON sin jQuery (sans getJSON)
9
A
Respuesta
3
Debería instalar su propia función JSON/AJAX. Hay algunos ejemplos here. No estoy seguro de lo buenos que son.
15
Si es la misma solicitud de dominio, entonces use window.XMLHttpRequest. Si se trata de distancia, y luego inyectar un elemento de script, se puede ver cómo lo hace jQuery:
// If we're requesting a remote document
// and trying to load JSON or Script with a GET
if (s.dataType === "script" && type === "GET" && remote) {
var head = document.getElementsByTagName("head")[0] || document.documentElement;
var script = document.createElement("script");
script.src = s.url;
if (s.scriptCharset) {
script.charset = s.scriptCharset;
}
// Handle Script loading
if (!jsonp) {
var done = false;
// Attach handlers for all browsers
script.onload = script.onreadystatechange = function() {
if (!done && (!this.readyState ||
this.readyState === "loaded" || this.readyState === "complete")) {
done = true;
success();
complete();
// Handle memory leak in IE
script.onload = script.onreadystatechange = null;
if (head && script.parentNode) {
head.removeChild(script);
}
}
};
}
// Use insertBefore instead of appendChild to circumvent an IE6 bug.
// This arises when a base node is used (#2709 and #4378).
head.insertBefore(script, head.firstChild);
// We handle everything using the script element injection
return undefined;
}
Utilice un JSON Parser. También puede usar eval
pero está mal visto a favor de un analizador JSON.
Aquí es parseJSON método interno de jQuery:
parseJSON: function(data) {
if (typeof data !== "string" || !data) {
return null;
}
// Make sure leading/trailing whitespace is removed (IE can't handle it)
data = jQuery.trim(data);
// Make sure the incoming data is actual JSON
// Logic borrowed from http://json.org/json2.js
if (/^[\],:{}\s]*$/.test(data.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, "@")
.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, "]")
.replace(/(?:^|:|,)(?:\s*\[)+/g, ""))) {
// Try to use the native JSON parser first
return window.JSON && window.JSON.parse ?
window.JSON.parse(data) :
(new Function("return " + data))();
} else {
jQuery.error("Invalid JSON: " + data);
}
},
Cuestiones relacionadas
- 1. Pasando datos JSON a .getJSON en jQuery?
- 2. jQuery - .getjson VS JSON .ajax
- 3. jQuery getJSON - ParseError ajax
- 4. jQuery Solicitudes getJSON múltiples
- 5. Combina múltiples archivos JSON en uno; recuperar utilizando jQuery/getJSON()
- 6. getJSON con jquery
- 7. ¿Cómo obtengo la respuesta JSON sin formato de una solicitud jQuery $ .getJSON()?
- 8. Obtener JSON remoto sin Jquery?
- 9. Cancelando un jQuery getJSON XMLHttpRequest
- 10. diferencia entre $ .getJSON() y $ .ajax() en jQuery
- 11. Enviar datos JSON a PHP utilizando XMLHttpRequest sin jQuery
- 12. Consumir servicios web JSON-RPC en .NET
- 13. Jquery getJSON problemas de dominio cruzado
- 14. IE8 getJSON datos en caché
- 15. $ .getJSON devolviendo datos en caché en IE8
- 16. Autocompletar jQuery datos utilizando JSON
- 17. Enviar datos JSON con jQuery
- 18. Consumir objeto JSON en PUT Restful Service
- 19. Consumir fechas JSON en un gridpanel EXTJs
- 20. jQuery getJSON con tiempo de espera
- 21. getJSON Callback Not Firing
- 22. jquery loop en datos Json usando $ .each
- 23. Jquery getJSON a la página externa de PHP
- 24. ¿Por qué $ .getJSON falla silenciosamente?
- 25. jquery lectura json anidado
- 26. JQuery no recibirá json?
- 27. Usando Jquery $ getJSON ¿Cómo creo dinámicamente datos para el parámetro [data] después de Url param?
- 28. jQuery getJSON que no pasa ningún valor al controlador
- 29. $ .getJSON botón de retroceso que muestra los datos de retorno JSON no la página
- 30. ¿Se deberían usar los métodos parseJSON/getJSON de jQuery?
Hola Vivek. ¿Podría agregar más detalles a su pregunta? ¿En qué idioma/marco estás trabajando? –
+1 Parece evidente que OP quiere saber cómo hacer una solicitud AJAX de datos JSON sin utilizar jQuery. No es tan dificil de entender. – user113716
@patrick: Bueno, hay personas lo suficientemente confusas para generar una discusión de comentarios en solo nueve palabras, así que diría que era evidente que era una pregunta pobre, independientemente de cuán capaz sea alguien de descifrarlo. – annakata