使用ajax获取数据

I am trying to get JSON data from an API by using this code:

$.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);
       },
});

In a Mobile app by cordova and framework7.

The browser console gives me the following error :

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.

Try this.

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)
                    }
                }
            }

</div>

Your endpoint needs to allow access from a null origin.

For example if your endpoint is a PHP file you can add this line to the top.

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

Can you try this at the beginning of your php file

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

Later, you change the * to the particular Ip address.

You can't make an arbitrary HTTP request to another server using XMLHttpRequest unless that server allows it by putting out an Access-Control-Allow-Origin header

You have 2 ways to solve this:

1-Add Access-Control-Allow-Origin header in the server response from API

headers: { 'Access-Control-Allow-Origin': '*' }

2-Use dataType: "jsonp" in your request

    dataType: "jsonp",                

You can even use below headers code in your PHP codes to the top.

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');