Procedure to Request a JSON File Or an XML File in the Local Host Using AJAX with Jquery Cross Domain File Request: Same Domain
Total Page:16
File Type:pdf, Size:1020Kb
Procedure to request a JSON file or an XML file in the local host Using AJAX with JQuery Cross Domain File Request: Access Across Domains For security reasons, modern browsers do not allow access across domains. This means that both the web page and the XML file it tries to load, must be located on the same server. The examples on W3Schools all open XML files located on the W3Schools domain. If you want to use the example above on one of your own web pages, the XML files you load must be located on your own server. Same Domain File Request: With Google Chrome: Need a local Web Server to request a file using AJAX with JQuery on the local host For example, in order to host these pages locally, MAMP’s local server is set up and used. Using the local server is necessary because when introducing JQuery’s getJson function, you will encounter cross origin domain requests which are not allowed when not on a server. With Firefox: No need to set a local Web Server to request a file using AJAX with JQuery on the local host /*use the JQuery function $.getJSON() to simply grab a JSON data file*/ function getJSON(){ $.getJSON("YelpOneBusinessJasonData.json", function(result){ jsondata = result; processJson(jsondata); }); } /*set our corresponding html via our json objects*/ function processJson(data){ //Set name first var name_html = document.getElementById('name'); name_html.innerText = data.name; … //Create our services and features table replacement_html = "<table>"; for(i in data.attributes){ replacement_html += "<tr>" if(typeof data.attributes[i] == 'object'){ var vals = Object.values(data.attributes[i]); var keys = Object.keys(data.attributes[i]); for(j in vals){ if(vals[j] == true){ replacement_html += "<td>" + keys[j] + "</td>"; replacement_html += "</tr>"; } } }else{ if(data.attributes[i] == true){ replacement_html += "<td>" + i + "</td>"; replacement_html += "</tr>"; } } } replacement_html += "</table>"; var services_html = document.getElementById('services'); services_html.innerHTML = replacement_html; } For XML, Consider using jQuery.parseXML If you need to parse large XML documents that you may not be able to completely hold in memory, consider using a SAX style parser like this one: https://github.com/isaacs/sax-js/ function getXML(){ 116. var xhttp = new XMLHttpRequest(); 117. xhttp.onreadystatechange = function (){ 118. if (this .readyState == 4 && this .status == 200){ 119. processXML( this ); 120. } 121. } 122. xhttp.open("GET", "restaurant_menu.xml", true ); 123. xhttp.send(); 124. } 125. 126. function processXML(data){ 127. var parser = new DOMParser(); 128. var xml = parser.parseFromString(data.responseText, "text/xml"); 129. 130. //Process breakfast 131. var html = document.getElementById("breakfast"); 132. var tempHtml = tableCreator(xml, "BREAKFAST"); 133. html.innerHTML += tempHtml; 134. 135. //Process brunch 136. html = document.getElementById("brunch"); 137. tempHtml = tableCreator(xml, "BRUNCH"); 138. html.innerHTML += tempHtml; 139. 140. //Process lunch 141. html = document.getElementById("lunch"); 142. tempHtml = tableCreator(xml, "LUNCH"); 143. html.innerHTML += tempHtml; 144. 145. //Process dinner 146. html = document.getElementById("dinner"); 147. tempHtml jQuery.parseXML( data ) Returns: XMLDocument Description: Parses a string into an XML document. • version added: 1.5 jQuery.parseXML( data ) o data Type: String a well-formed XML string to be parsed jQuery.parseXML uses the native parsing function of the browser to create a valid XML Document. This document can then be passed to jQuery to create a typical jQuery object that can be traversed and manipulated. Example: Create a jQuery object using an XML string and obtain the value of the title node. <!doctype html> 1 <html lang ="en" > 2 <head> 3 <meta charset ="utf-8" > 4 <title> jQuery.parseXML demo </title> 5 <script src ="https://code.jquery.com/jquery-1.10.2.js" ></script> 6 </head> 7 <body> 8 <p id ="someElement" ></p> 9 <p id ="anotherElement" ></p> 10 11 <script> 12 var xml = "<rss version='2.0'><channel><title>RSS Title</title></channel></rss>" , 13 xmlDoc = $.parseXML( xml ), 14 $xml = $( xmlDoc ), 15 $title = $xml.find( "title" ); 16 // Append "RSS Title" to #someElement 17 $( "#someElement" ).append( $title.text() ); 18 19 // Change the title to "XML Title" 20 $title.text( "XML Title" ); 21 22 // Append "XML Title" to #anotherElement 23 $( "#anotherElement" ).append( $title.text() ); </script> 24 25 </body> 26 </html> 27 28 29 30 jQuery.ajax( url [, settings ] ) Returns: jqXHR Description: Perform an asynchronous HTTP (Ajax) request. • version added: 1.5 jQuery.ajax( url [, settings ] ) o url Type: String A string containing the URL to which the request is sent. o settings Type: PlainObject A set of key/value pairs that configure the Ajax request. All settings are optional. A default can be set for any option with $.ajaxSetup() . See jQuery.ajax( settings ) below for a complete list of all settings. • version added: 1.0 jQuery.ajax( [settings ] ) o settings Type: PlainObject A set of key/value pairs that configure the Ajax request. All settings are optional. A default can be set for any option with $.ajaxSetup() . accepts (default: depends on DataType ) Type: PlainObject A set of key/value pairs that map a given dataType to its MIME type, which gets sent in the Accept request header. This header tells the server what kind of response it will accept in return. For example, the following defines a custom type mycustomtype to be sent with the request: 1 $.ajax({ 2 accepts: { 3 mycustomtype: 'application/x-some-custom-type' 4 }, 5 // Instructions for how to deserialize a `mycustomtype` 6 converters: { 7 'text mycustomtype' : function(result) { 8 // Do Stuff 9 return newresult; 10 } 11 }, 12 13 // Expect a `mycustomtype` back from server dataType: 'mycustomtype' 14 }); 15 16 Note: You will need to specify a complementary entry for this type in converters for this to work properly. async (default: true ) Type: Boolean By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false . Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active. As of jQuery 1.8 , the use of async: false with jqXHR ($.Deferred ) is deprecated; you must use the success/error/complete callback options instead of the corresponding methods of the jqXHR object such as jqXHR.done() . beforeSend Type: Function ( jqXHR jqXHR, PlainObject settings ) A pre-request callback function that can be used to modify the jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object before it is sent. Use this to set custom headers, etc. The jqXHR and settings objects are passed as arguments. This is an Ajax Event . Returning false in the beforeSend function will cancel the request. As of jQuery 1.5 , the beforeSend option will be called regardless of the type of request. cache (default: true, false for dataType 'script' and 'jsonp' ) Type: Boolean If set to false , it will force requested pages not to be cached by the browser. Note: Setting cache to false will only work correctly with HEAD and GET requests. It works by appending "_={timestamp}" to the GET parameters. The parameter is not needed for other types of requests, except in IE8 when a POST is made to a URL that has already been requested by a GET. complete Type: Function ( jqXHR jqXHR, String textStatus ) A function to be called when the request finishes (after success and error callbacks are executed). The function gets passed two arguments: The jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object and a string categorizing the status of the request ("success" , "notmodified" , "nocontent" , "error" , "timeout" , "abort" , or "parsererror" ). As of jQuery 1.5 , the complete setting can accept an array of functions. Each function will be called in turn. This is an Ajax Event . contents Type: PlainObject An object of string/regular-expression pairs that determine how jQuery will parse the response, given its content type. (version added: 1.5 ) contentType (default: 'application/x-www-form-urlencoded; charset=UTF-8' ) Type: Boolean or String When sending data to the server, use this content type. Default is "application/x-www- form-urlencoded; charset=UTF-8", which is fine for most cases. If you explicitly pass in a content-type to $.ajax() , then it is always sent to the server (even if no data is sent). As of jQuery 1.6 you can pass false to tell jQuery to not set any content type header. Note: The W3C XMLHttpRequest specification dictates that the charset is always UTF-8; specifying another charset will not force the browser to change the encoding. Note: For cross-domain requests, setting the content type to anything other than application/x-www-form-urlencoded , multipart/form-data , or text/plain will trigger the browser to send a preflight OPTIONS request to the server. context Type: PlainObject This object will be the context of all Ajax-related callbacks. By default, the context is an object that represents the Ajax settings used in the call ( $.ajaxSettings merged with the settings passed to $.ajax ). For example, specifying a DOM element as the context will make that the context for the complete callback of a request, like so: 1 $.ajax({ 2 url: "test.html" , 3 context: document.body 4 }).done(function() { $( this ).addClass( "done" ); 5 }); 6 converters (default: {"* text": window.String, "text html": true, "text json": jQuery.parseJSON, "text xml": jQuery.parseXML} ) Type: PlainObject An object containing dataType-to-dataType converters. Each converter's value is a function that returns the transformed value of the response. (version added: 1.5 ) crossDomain (default: false for same-domain requests, true for cross-domain requests ) Type: Boolean If you wish to force a crossDomain request (such as JSONP) on the same domain, set the value of crossDomain to true . This allows, for example, server-side redirection to another domain. (version added: 1.5 ) data dataType (default: Intelligent Guess (xml, json, script, or html) ) Type: String The type of data that you're expecting back from the server.