Article From:https://www.cnblogs.com/ouguangqiang/p/9176803.html

 

Need to meet the needs of Ajax cross domain recently

First, let’s look at what kind of mistakes the Ajax cross domain requests do without any special processing.

Client code:

<script type="text/javascript">
    $.ajax({
        url: 'http://localhost/test/respone.php',
        type: 'get',
        dataType: 'json',
        success:function (res) {
            console.log(res);
        }
    });
    
</script>

Server-side code:

<?php
echo json_encode(['name'=>'ogq','age'=>18]);

?>

Running results:

Tip: Failed to load http://localhost/test/respone.php: No’Access-Control-Allow-Origin’header is presEnt on the requested resource. Origin’http://my.com’is therefore not allowed therefore error

This is because the browser Ajax can not be spanning the domain. Here is a Ajax cross domain request and return that I simply do after searching the data.

Client code:

<script type="text/javascript">
    $.ajax({
        url: 'http://localhost/test/respone.php',
        type: 'get',
        dataType: 'jsonp',
        success:function (res) {
            console.log(res);
        }
    });
    
</script>

  That’s right, just changing the dataType: “JSON” to “jsonp”.

Then the server – side code:

<?php

echo $_REQUEST['callback'],'('.json_encode(['name'=>'ogq','age'=>18]),')';
?>

  At the request, the output results

This makes it normal to cross the domain

ps:Without a deep study, it can be used normally. Hee

 

Link of this Article: Simple ajax cross domain request

Leave a Reply

Your email address will not be published. Required fields are marked *