XMLHttpRequest XMLHttpRequest que puede buscar ficheros desde el servidor.
XMLHttpRequest objectXMLHttpRequest object requests page from serverXMLHttpRequest fires an event when data arrives
Uso de Javascript para obtener más contenido desde el servidor sin navegar a otra página
let xhr = new XMLHttpRequest();
xhr.open(method, url, [async/sync]);
xhr.onload = function() { /* handle success */ };
xhr.onerror = function() { /* handle failure */ };
xhr.send();
let xhr = new XMLHttpRequest();
xhr.open("GET", "data.txt");
xhr.onload = function() { alert(this.responseText); };
xhr.onerror = function() { alert("ERROR!"); };
xhr.send();
Como se ha mencionado antes no se aconseja usar el método de llamada AJAX de XML sobre HTML
$.ajax({
"url": "http://foo.com",
"option" : "value",
"option" : "value",
...
"option" : "value"
});
$.ajax() methodurl to fetch, as a String,type of the request, GET or POSTXMLHttpRequest; works well in all browsers$.ajax() options| option | description |
|---|---|
url |
The URL to make a request from |
type |
whether to use POST or GET |
data |
an object literal filled with query parameters and their values |
dataType |
The type of data you are expecting to recieve, one of: "text", "html", "json", "xml" |
timeout |
an amount of time in seconds to wait for the server before giving up |
success |
event: called when the request finishes successfully |
error |
event: called when the request fails |
complete |
event: called when the request finishes successfully or erroneously |
$.ajax({
"url": "foo/bar/mydata.txt",
"type": "GET",
"success": myAjaxSuccessFunction,
"error": ajaxFailure
});
function myAjaxSuccessFunction(data) {
// do something with the data
}
function ajaxFailure(xhr, status, exception) {
console.log(xhr, status, exception);
}
success and error eventsThe data passed to your success handler will be in whatever format you specified in the dataType option
dataType of text returns raw text no matter its apparent data typedataType of html returns raw html textdataType of xml returns an XML document objectdataType of json returns a JSON object
$.ajax(
"url": "http://foo.com",
"type": "GET",
"success": functionName,
"error": ajaxFailure
});
...
function ajaxFailure(xhr, status, exception) {
console.log(xhr, status, exception);
}
Rather than specify all of the options in an object literal...
$.ajax({
"url": "http://foo.com",
"type": "GET",
"success": functionName,
"error": ajaxFailure
});
one can pass the URL as the first parameter and the rest as an object literal.
$.ajax("http://foo.com", {
"type": "GET",
"success": functionName,
"error": ajaxFailure
});
Why? It makes it even easier to see what this AJAX request is doing.
$.get() and $.post()| function | description |
|---|---|
$.ajax() |
A general function for making AJAX requests, other AJAX functions rely on this |
$.get() |
makes a GET request via AJAX |
$.post() |
makes a POST request via AJAX |
Why bother making the distinction if it all boils down to a call to $.ajax() under the hood
XMLHttpRequest security restrictions
http://www.foo.com/a/b/c.html can only fetch fromwww.foo.comMy note: BEGIN TO: Alice Smith (alice@example.com) FROM: Robert Jones (roberto@example.com) SUBJECT: Tomorrow's "Birthday Bash" event! MESSAGE (english): Hey Bob, Don't forget to call me this weekend! PRIVATE: true END
<?xml version="1.0" encoding="UTF-8"?> <note private="true"> <to>Alice Smith (alice@example.com)</to> <from>Robert Jones (roberto@example.com)</from> <subject>Tomorrow's "Birthday Bash" event!</subject> <message language="english"> Hey Bob, Don't forget to call me this weekend! </message> </note>
<element attribute="value">content</element>
h1, div, img, etc.id/class, src, href, etc.<?xml version="1.0" encoding="UTF-8"?> <!-- XML prolog --> <note private="true"> <!-- root element --> <to>Alice Smith (alice@example.com)</to> <from>Robert Jones (roberto@example.com)</from> <subject>Tomorrow's "Birthday Bash" event!</subject> <message language="english"> Hey Bob, Don't forget to call me this weekend! </message> </note>
<?xml ... ?> header tag (prolog)note)<measure number="1"> <attributes> <divisions>1</divisions> <key><fifths>0</fifths></key> <time><beats>4</beats></time> <clef> <sign>G</sign><line>2</line> </clef> </attributes> <note> <pitch> <step>C</step> <octave>4</octave> </pitch> <duration>4</duration> <type>whole</type> </note> </measure>
book, title, authorkey, pitch, note
$.get("foo.xml")
.done(functionName);
function functionName(xmlDom) {
// do stuff with the xmlDom just like you would with the HTML dom
}
xmlDom is the XML equivalent of document in the HTML DOM, it is not the root tag
<?xml version="1.0" encoding="UTF-8"?> <categories> <category>children</category> <category>computers</category> ... </categories>
To get a list of all nodes that use a given element:
var elms = node.getElementsByTagName("tag");
To get the text inside of a node:
var text = node.firstChild.nodeValue;
To get an attribute's value from a node:
var attrValue = node.getAttribute("name");
nodeName, nodeType, nodeValue, attributesfirstChild, lastChild, childNodes, nextSibling, previousSibling, parentNodegetElementsByTagName, getAttribute, hasAttribute[s], hasChildNodesappendChild, insertBefore, removeChild, replaceChildYou use the same jQuery functions to interact with the XML DOM, with one minor tweak:
$(xmlDom).find("tagName");
// You can use complicated CSS selectors
$(xmlDom).find("ingredient[quantity='5']");
$(xmlDom).find("tagName")
.parent()
.children()
.each(function);
$(xmlDom).find("directions")
.attr("time", "0")
.text("make the dish :P");
<?xml version="1.0" encoding="UTF-8"?> <employees> <lawyer money="99999.00" /> <janitor name="Ed"> <vacuum model="Hoover" /> </janitor> <janitor name="Bill">no vacuum, too poor</janitor> </employees>
// how much money does the lawyer make? $(xmlDom).find("lawyer").attr("money"); // "99999.00" // array of 2 janitors var janitors = $(xmlDom).find("janitor"); janitors.find("vacuum").attr("model"); // "Hoover" janitors.last().text(); // "no vacuum, too poor"
<?xml version="1.0" encoding="UTF-8"?> <bookstore> <book category="cooking"> <title lang="en">Everyday Italian</title> <author>Giada De Laurentiis</author> <year>2005</year><price>30.00</price> </book> <book category="computers"> <title lang="en">XQuery Kick Start</title> <author>James McGovern</author> <year>2003</year><price>49.99</price> </book> <book category="children"> <title lang="en">Harry Potter</title> <author>J K. Rowling</author> <year>2005</year><price>29.99</price> </book> <book category="computers"> <title lang="en">Learning XML</title> <author>Erik T. Ray</author> <year>2003</year><price>39.95</price> </book> </bookstore>
// make a paragraph for each book about computers $(xmlDom).find("book[category='computer']").each(function(idx, e) { // extract data from XML var title = $(e).find("title").text(); var author = $(e).find("author").text(); // make an HTML <p> tag containing data from XML $("<p>") .text(title + ", by " + author) .appendTo($(document.body)); });
JavaScript Object Notation (JSON): Data format that represents data as a set of JavaScript objects
var person = {
"name": "Philip J. Fry", // string
"age": 23, // number
"weight": 172.5, // number
"friends": ["Farnsworth", "Hermes", "Zoidberg"], // array
"getBeloved": function() { return this.name + " loves Leela"; }
};
alert(person.age); // 23
alert(person["weight"]); // 172.5
alert(person.friends[2])); // Zoidberg
alert(person.getBeloved()); // Philip J. Fry loves Leela
this["fieldName"] or .fieldName syntax if fieldName is a legal Javascript identifierweight above)<?xml version="1.0" encoding="UTF-8"?> <note private="true"> <from>Alice Smith (alice@example.com)</from> <to>Robert Jones (roberto@example.com)</to> <to>Charles Dodd (cdodd@example.com)</to> <subject>Tomorrow's "Birthday Bash" event!</subject> <message language="english"> Hey guys, don't forget to call me this weekend! </message> </note>
{
"private": "true",
"from": "Alice Smith (alice@example.com)",
"to": [
"Robert Jones (roberto@example.com)",
"Charles Dodd (cdodd@example.com)"
],
"subject": "Tomorrow's \"Birthday Bash\" event!",
"message": {
"language": "english",
"text": "Hey guys, don't forget to call me this weekend!"
}
}
| method | description |
|---|---|
JSON.parse(string)
|
converts the given string of JSON data into an equivalent JavaScript object and returns it |
JSON.stringify(object)
|
converts the given object into a string of JSON data (the opposite of JSON.parse)
|
JSON.parse on it to convert it into an objectvar data = JSON.parse(jsonString);
{
"window": {
"title": "Sample Widget",
"width": 500,
"height": 500
},
"image": {
"src": "images/logo.png",
"coords": [250, 150, 350, 400],
"alignment": "center"
},
"messages": [
{"text": "Save", "offset": [10, 30]}
{"text": "Help", "offset": [ 0, 50]},
{"text": "Quit", "offset": [30, 10]},
],
"debug": "true"
}
Given the JSON data at right, what expressions would produce:
var title = data.window.title; var coord = data.image.coords[2]; var len = data.messages.length; var y = data.messages[len - 1].offset[1];
$.get("foo.json")
.done(functionName);
function functionName(jsonObj) {
// do stuff with the jsonObj
}