简体   繁体   中英

How to send cross-domain and get respond

I would like to set form where i can send some informations to another domain cross-domain and getting response back.

Let say I've the following database table info

I would like to set form where i can send some informations to another domain cross-domain and getting response back.

I've made many searching for tutorial but all are without full example to study so this example will helps me a lot.

Let say I've the following database table info

---------------------
| ID |  Name  | Age |
---------------------
| 12 |  Dave  | 18  |
---------------------
| 34 |  Eva   | 17  |
---------------------
| 31 | Carry  | 19  |
---------------------

Now the HTML page index.html on www.site_1.com and this form will sent cross-domain both name and age to http://www.site_2.com/data.php

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>

<form id="form" name="form" method="post">
<fieldset>
<label for="name">Name:</label>
<input class="text" id="name" name="name" size="20" type="text" />

<label for="name">Age:</label>
<input class="text" id="age" name="age" size="20" type="text" />

<input type="submit" value="submit" id="submit" name="submit"/>
</fieldset>
</form>

<script>
$( document ).ready(function() {

    $('form').submit(function(event){
        event.preventDefault();

        var name = $(this).find("#name").val();
        var age = $(this).find("#age").val();

        $.ajax({
            type: 'POST',
            crossdomain: true,
            //data: 'name=' + name + '&age=' + age,
            data: {name : name, age : age},
            url: 'http://www.site_2.com/data.php',
            success: function(data){
                if(data == 1){
                    alert("YES!");
                }else{
                    alert("NO");
                }
            },
            error: function(){
                alert('Error');
            }
        });
        return false;
    });
});
</script>

Now on www.site_2.com here is the code of data.php

<?PHP
// Suppose it already connected to DB

// for cross-domain
switch ($_SERVER['HTTP_ORIGIN']) {
    case 'http://localhost': case 'https://localhost':
    header('Access-Control-Allow-Origin: '.$_SERVER['HTTP_ORIGIN']);
    header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
    header('Access-Control-Max-Age: 1000');
    header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
    break;
}

// getting sent informations
$name = $_POST['name'];
$age = $_POST['age'];

// do some query
$a1 = "select id from info where name = '$name'";
$query = mysql_query($a1) or die(mysql_error());
$get = mysql_fetch_array($query);

// get the id
$id = $get['id'];

// i want it to send it back
echo $id;
?>

you code works if your www.site_1.com is localhost . you will get a plain text response 1 (if the id is 1). if you have a lot data to return you can encode it as json using json_encode in server, and decode it using JSON.parse in client. using echo to send data back is fine. everything you echo will be in the response body

if it is not working in your machine, there are some reasons i can think about

  1. $.ajax part has some trouble. i only tested the server part using different client code.
  2. your server got some trouble in database operations.
  3. your client code is not in localhost domain, so the part for set header to allow CORS is never executed and you will see error in console like this XMLHttpRequest cannot load http://www.site_2.com/info.php. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://www.site_1.com' is therefore not allowed access. XMLHttpRequest cannot load http://www.site_2.com/info.php. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://www.site_1.com' is therefore not allowed access.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM