简体   繁体   English

如何发送跨域并获得响应

[英]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 假设我有以下数据库表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 现在, www.site_1.com上的HTML页面index.html ,此表单会将跨域的nameage发送到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 现在在www.site_2.comdata.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 . 如果您的www.site_1.comlocalhost则您的代码有效。 you will get a plain text response 1 (if the id is 1). 您将获得纯文本响应1 (如果id为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. 如果要返回的数据很多,则可以在服务器中使用json_encode将其编码为json,并在客户端中使用JSON.parse对其进行解码。 using echo to send data back is fine. 使用echo将数据发送回去就可以了。 everything you echo will be in the response body echo所有内容都将在响应正文中

if it is not working in your machine, there are some reasons i can think about 如果它在您的机器上不起作用,则有一些我可以考虑的原因

  1. $.ajax part has some trouble. $.ajax部分有一些麻烦。 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. 您的客户端代码不在localhost域中,因此永远不会执行用于设置标头以允许CORS的部分,并且您会在控制台中看到类似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. 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.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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