Home >Web Front-end >JS Tutorial >Why Does AJAX Fail to Load Cross-Domain HTML Unless JSONP is Used, and How Can This Be Solved?

Why Does AJAX Fail to Load Cross-Domain HTML Unless JSONP is Used, and How Can This Be Solved?

Barbara Streisand
Barbara StreisandOriginal
2024-12-29 19:32:12742browse

Why Does AJAX Fail to Load Cross-Domain HTML Unless JSONP is Used, and How Can This Be Solved?

Loading Cross-Domain Endpoint with AJAX

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:

  • CORS Anywhere: Automatically adds CORS headers to proxied requests.
$.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;
  }
});
  • Whatever Origin: Facilitates cross-domain JSONP access.
$.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);
  }
);
  • CORS Proxy: Simplifies CORS requests for any website.
$.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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn