The jQuery cross-domain Ajax will fail.

Asked 2 years ago, Updated 2 years ago, 65 views

Testing on localhost to run js across domains

html side

jQuery.ajax({
    type: 'GET',
    url —Url,
    dataType: "jsonp",
    crossDomain: true,
    success:function(res){
        alert("success");
    },
    error: function(res){
        alert("error");
    }
});

php side

<?php
header('Access-Control-Allow-Origin:*');
header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept');
echo json_encode (123456789);

If you execute the above code, you will see a dialog called "error".
I think it's the simplest form, but I don't know where the cause is.
I tried using echo as a string or array, but the situation remained the same.

dataType: Delete "jsonp to display "success".

Please give me some advice.

php ajax

2022-09-29 22:06

2 Answers

The implementation on the php side is JSON, not JSONP.

With JSONP

callback(123456789);

You should return the JavaScript


2022-09-29 22:06

It worked by doing the following.Thank you for your advice.

html side

jQuery.ajax({
      type: 'GET',
      url —Url,
      dataType: "jsonp",
      jsonpCallback: 'callback',
      success:function(res){
        alert("success");
    },
    error: function(res){
        alert("error");
    }
});

php side

<?php
header('Access-Control-Allow-Origin:*');
header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept');
echo "callback(".json_encode("123456789").")";


2022-09-29 22:06

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.