Problem:
You encounter difficulties loading a cross-domain HTML page using AJAX unless the dataType is set to "jsonp." Even when using JSONP, the browser anticipates a script mime type but instead receives "text/html."
Solution 1: Utilizing Third-Party Proxies
Due to security concerns with third-party proxies tracking user data, their usage with private information is discouraged. However, they may be suitable for public data scenarios.
Consider the following proxy options:
$.ajaxPrefilter(function (options) { if (options.crossDomain && jQuery.support.cors) { var http = (window.location.protocol === 'http:' ? 'http:' : 'https:'); options.url = http + '//cors-anywhere.herokuapp.com/' + options.url; } });
$.ajaxSetup({ scriptCharset: "utf-8", contentType: "application/json; charset=utf-8" }); $.getJSON('http://whateverorigin.org/get?url=' + encodeURIComponent('http://google.com') + '&callback=?', function (data) { console.log("> ", data); $("#viewer").html(data.contents); } );
$.get( 'http://www.corsproxy.com/' + 'en.wikipedia.org/wiki/Cross-origin_resource_sharing', function (response) { console.log("> ", response); $("#viewer").html(response); } );
Solution 2: Establishing Your Backend Proxy
The most secure approach is to create a proxy on the back-end, resolving the cross-domain issue.
The above is the detailed content of Why Does AJAX Fail to Load Cross-Domain HTML Unless JSONP is Used, and How Can This Be Solved?. For more information, please follow other related articles on the PHP Chinese website!