使用 ajax 获取数据

Get data using ajax

我正在尝试使用以下代码从 API 中获取 JSON 数据:

$.ajax({

xhrFields: {
    withCredentials: true
},
beforeSend: function (xhr) {
    xhr.setRequestHeader('Authorization', 'Basic ' + btoa('user:pass'));
},

url: 'http://127.0.0.1/appcpanel/appapi/tribe',
type: 'GET',
dataType: 'jsonp',
success: function (data) {
console.log(data);
       },
});

在 cordova 和 framework7 的移动应用程序中。

浏览器控制台出现以下错误:

XMLHttpRequest cannot load http://127.0.0.1/appcpanel/appapi/tribe. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://192.168.1.2:3000' is therefore not allowed access. The response had HTTP status code 404.

试试这个。

var Variable = "1";
        $.ajax({
            type: "POST",
            url: "url here",
            data: '{"ID" : ' + Variable + '}',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (jsonData) {
                if (jsonData.d != "") {
                    if (jsonData.d != "")
                    {
                        console.log(jsonData.d)
                    }
                }
            }

您的端点需要允许从空源访问。

例如,如果您的端点是一个 PHP 文件,您可以将此行添加到顶部。

header('Access-Control-Allow-Origin: *');

你能在 php 文件的开头试试这个吗

header('Access-Control-Allow-Origin: *');
header('Content-type: application/json');

稍后,您将 * 更改为特定的 IP 地址。

您不能使用 XMLHttpRequest 向另一台服务器发出任意 HTTP 请求,除非该服务器通过发出 Access-Control-Allow-Origin header

允许它

你有两种方法可以解决这个问题:

1-在来自 API

的服务器响应中添加 Access-Control-Allow-Origin header
headers: { 'Access-Control-Allow-Origin': '*' }

2-在您的请求中使用数据类型:"jsonp"

    dataType: "jsonp",                

您甚至可以在 PHP 代码中使用下面的 headers 代码到顶部。

header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
header('Access-Control-Allow-Methods: GET, POST, PUT');