Freigeben über


Using XML HTTP Request in JavaScript to parse any Text, HTML or XML files on a remote location over HTTP (MOSS Example)

We all met the "View Source" functionality in browsers. You just right click the page, and click on "View Source"; Notepad (most probably) will launch up and display the page markup. If you are using a server side technology like ASP.NET, you will only get the HTML markup that renders the page in the browser. You will not be able to see any source code even if it is in-lined.

image

What if you want to read the HTML markup to a variable in your script? e.g. let's imagine that you have this complicated custom list. Users will need to read a small write up before they start using it. On your first visit, the list should be hidden and the write up will be displayed. Once you create your first item, the write up will disappear. The write up will not be displayed in any future visits. (Sorry had to add the MOSS flavor Smile with tongue out)

Approaching a solution is simple:

image

To be able to load the page markup into JavaScript we use a XML HTTP Request. Having XML in the name does not limit its usage to XML files only, it can be used over any raw text file e.g. HTML files. However, we can't use it with binary files.

To use the XML HTTP Request to parse a remote page, we go through 2 steps:

  1. Create an XML HTTP Request:

    image

  2. Request the page through XML HTTP:

    image

The entire page markup now is loaded into the variable "htmlmarkup". Now we need to search for the user name in the string, but we have one problem left: we have no clue about the current logged in user.

In order to sort this we use WinNetwork:

image

Let's search for any created documents that belong to the logged in user, if we find any then we hide the div that contains the small write up.

image

If no matches found, the function will return "-1". The div name is "SmallWriteUp". We use the "getElementById" method under "document" in HTML DOM to set the visibility property of the div to hidden.

Traaaaa Smile we're done with our small example! To wrap up, we learned how to load any text base files rendering markup such as XML, HTML, or even ASP.NET into JavaScript variables using XML HTTP Requests. We went over WinNetwork and used it in JavaScript to know who the current logged in user is and finally we used JavaScript's string search function.

References:

Comments

  • Anonymous
    August 20, 2013
    What about cross-origin requests? Does the code still work?