Procedure to request a JSON file or an XML file in the ...

[Pages:23]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 = ""; for(i in data.attributes){ replacement_html += "" 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 += "" + keys[j] + ""; replacement_html += ""; } } }else{ if(data.attributes[i] == true){ replacement_html += "" + i + ""; replacement_html += ""; }

} } replacement_html += ""; 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:

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.5jQuery.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.

1

2

3

4 jQuery.parseXML demo

5

6

7

8

9

10

11

12 var xml = "RSS Title",

13 xmlDoc = $.parseXML( xml ),

14 $xml = $( xmlDoc ),

15 $title = $xml.find( "title" );

16 17 // Append "RSS Title" to #someElement

$( "#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() ); 24

25

26

27

28

29

30

jQuery.ajax( url [, settings ] )Returns: jqXHR Description: Perform an asynchronous HTTP (Ajax) request.

? version added: 1.5jQuery.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.0jQuery.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 14 dataType: 'mycustomtype'

}); 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

................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download