Use jQuery and YQL to load external content in Ajax Mode

Source: Internet
Author: User
Let's take a look at how to use jQuery to load external content (in other domains) in Ajax mode. All the code here can be downloaded from GitHub or on this demo page, so you do not need to copy or paste it. OK. Ajax is easily implemented through jQuery. Most solutions are... SyntaxHighlighter. all ();

Let's take a look at how to use jQuery to load external content (in other domains) in Ajax mode. All the code here can be downloaded from GitHub or on this demo page, so you do not need to copy or paste it.
OK. Ajax is easy to implement through jQuery. Most solutions have a few lines of code:
$ (Document). ready (function () {functions ('.ajaxtrigger'{.click(function({{}('{target'{.load('ajaxcontent.html ');});});
Check this simple but crude Ajax demo to see the result.
This will convert all elements with the ajaxtriggerclass into a sender to export ajaxcontent.html and display the content in the element with the ID of target.
This is not good, because most of the time this means that people will use empty links such as click me, but this is not the question we want to discuss now. I am writing a longer article about all the techniques for enhancing Ajax availability and accessibility.
To make it reusable, it can be as follows:
$ (Document ). ready (function () {$ ('. ajaxtrigger '). click (function () {$ ('# target '). load ($ (this ). attr ('href '); return false ;});});
In this way, you can use load some content to load the content, and all JavaScript code can be reused.
View this reusable Ajax demo to see the result.
The problem I want to solve occurs when I click the second link in the demo page: loading external content fails because Ajax does not allow cross-origin loading of content. This means that the http://icant.co.uk/"class =" ajaxtrigger "> see my portfolio loading Ajax content will fail and no prompt is prompted. Even if you click this link for countless times, nothing will happen. One way to avoid this is to simply let the browser load the document, but the premise is that the user really wants to load external links.
You can view the results of this demonstration that allows loading external links.
$ (Document ). ready (function () {$ ('. ajaxtrigger '). click (function () {var url = $ (this ). attr ('href '); if (url. match ('^ http') {return true;} else {$ ('# target '). load (url); return false ;}});});
Use PHP proxy
If you browse the Web, you will find that most of the solutions are PHP (or other languages) proxy scripts. For example, the following uses the cURL proxy. php proxy script:

Then you can use this script (using a proxy) with a slight modification ):
$ (Document ). ready (function () {$ ('. ajaxtrigger '). click (function () {var url = $ (this ). attr ('href '); if (url. match ('^ http') {url = 'proxy. php? Url = '+ url ;}$ (' # target'). load (url); return false ;});});
Using such a proxy script is still a stupid method, because people can use this script to load any documents on your server without filtering, and display the content on your own page (rename the link with firebug to see any content on your server). They can use it to insert a mass mailing script into the document, or simply use it to redirect to any other Web Resource and make your server look like the server that sends the request. Spam makers have a place to show their talents.
Use whitelist and filter proxy
Therefore, to use a proxy, you must ensure that there is a white list of recognized Uris. In addition, except for the subject of another HTML document, it is better to remove the other content. Another good way is to filter scripts. This avoids displaying errors and executing scripts that you do not want to execute on the website.
As shown below:
] *>/Msi ', '', $ output); $ content = preg_replace ('/. */Msi ', '', $ content); $ content = preg_replace ('/ ] *>/Msi ', '', $ content); $ content = preg_replace ('/[r | n] +/msi ','', $ content ); $ content = preg_replace ('/<-- [Ss] *? -->/Msi ', '', $ content); $ content = preg_replace ('/ ] *> [Ss] *?/Msi ', '', $ content); $ content = preg_replace ('/ ] *> [Ss] *? Script/msi ', '', $ content); $ content = preg_replace ('/ /Msi ', '', $ content); echo $ content;} else {echo 'error: URL not allowed to load here.' ;}?>
YQL pure JavaScript Solution
However, what if you do not have the right to access the server, or you only want to use JavaScript? Don't worry, this can be done. YQL can load any HTML document and return it in JSON format. JQuery has a good interface for loading JSON, so using it with YQL can achieve our goal.
It is easy to get HTML from YQL. Use the following statement:
Select * from html where url = "http://icant.co.uk"
YQL can also do the following:
• Load and clear HTML documents
• Use HTML Tidy to run HTML documents to delete bad tags
• Cache HTML
• Only the body content of HTML is returned, so no other styles need to be processed except inline styles.
The data output format can be XML or JSON. If a callback parameter is defined for JSON, it indicates that the JSON-P is used and all HTML is saved in a JavaScript Object-this is not suitable for restructuring.
Foo ({"query": {count ", created", lang ", updated", http://query.yahoo [... whatever...] k % 22 "title =" "> uri", "results": {"body": {"div": {id ", div ", h1-everything Christian Heilmann "},{ id", "div": [{div this and me ","[... and so on...] }}}}});
When a callback with XML output is defined, you will get a function call that uses HTML data as a string in the array, much simpler:
Foo ({"query": {count ", created", lang ", updated", http://query.y [... who "title =" "> uri cares...] % 22 "}," results ":["N icant. co. uk-everything Christian Heilmannn... and so on... "]});
Use the getJSON () method of jQuery to access the YQL endpoint, which is easy to implement:
$. GetJSON ("http://query.yahooapis.com/v1/public/yql? "+" Q = select % 20 * % 20 from % 20 html % 20 where % 20url % 3D % 22 "+ encodeURIComponent (url) + "% 22 & format = xml' & callback =? ", Function (data) {if (data. results [0]) {var data = filterData (data. results [0]); container.html (data);} else {var errormsg ='

Error: cocould not load the page.

'; Container.html (errormsg );}});
The cross-origin Ajax Solution Using jQuery and YQL can be obtained through combination:
$ (Document ). ready (function () {var container =$ ('# target'); $ ('. ajaxtrigger '). click (function () {doAjax ($ (this ). attr ('href '); return false;}); function doAjax (url) {// if it is an external URI if (url. match ('^ http') {// call YQL $. getJSON ("http://query.yahooapis.com/v1/public/yql? "+" Q = select % 20 * % 20 from % 20 html % 20 where % 20url % 3D % 22 "+ encodeURIComponent (url) + "% 22 & format = xml' & callback =? ", // This function gets the data from the successful JSON-P calling function (data) {// if there is data, filter it and present it out if (data. results [0]) {var data = filterData (data. results [0]); container.html (data); // otherwise, an error occurs.} else {varerrormsg ='

Error: cocould not load the page.

'; Container.html (errormsg) ;}}); // if it is not an external URI, use the Ajax load () method} else {$ (' # target '). load (url) ;}// filter out some bad things function filterData (data) {data = data. replace (/ ] *>/G, ''); data = data. replace (/[r | n] +/g, ''); data = data. replace (/<-- [Ss] *? -->/G, ''); data = data. replace (/ ] *> [Ss] *?/G, ''); data = data. replace (/ ] *> [Ss] *? Script/g, ''); data = data. replace (/ /, ''); Return data ;}});
Of course, this example is still rough. The actual Ajax solution should consider timeout and failure to find the document. View the complete code with loading indicator, exception handling, and yellow fading Technology for inspiration.

From Turing Education

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.