错误:“Origin null 不允许由 Access-Control-Allow-Origin 使用 dataType

Error: “Origin null is not allowed by Access-Control-Allow-Origin” when using dataType text/html accessing a php file using JQuery's ajax method

本文关键字:Access-Control-Allow-Origin 使用 dataType 不允许 null Origin 错误      更新时间:2023-09-26

为什么我在使用dataType文本和html时在chrome上收到此错误?如果我回显一个 JavaScript 并将 dataType 设置为脚本,它会起作用?如何从 php 文件中回显非 JavaScript 数据?

    client side:
    $.ajax({
    url: "http://localhost:8888/test.php",
    type: "GET",
    dataType: "text",
    success: function (data) {
    alert(data);
    }
    php file (test.php):
    <?php
    echo "Hello";
     ?>php file (test.php):

您遇到跨域请求问题(很可能是因为客户端脚本未从 http://localhost:8888/提供(。

通过将dataType设置为 script,您可以启用一种类型的请求,该请求通过将<script/>标记注入页面 DOM 来处理跨域请求。实现这一点的代码在 GitHub 上。

您需要:

  • 通过从与 PHP 相同的主机和端口提供客户端脚本来解决跨域请求问题。
  • 更改脚本以返回 JSONP。