如何跨域发送Ajax请求?

时间:2015-03-13 21:57:47

标签: javascript php ajax

过去几天我一直试图找出如何通过ajax请求跨域通信。

我有这个档案......

<?php

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

?>
<script>
    function send(user){
        var hr = new XMLHttpRequest();
        var url = "http://forumchest.com/kb_exchange.php";
        var data = "user="+user;
        hr.open("POST", url, true);
        hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        hr.onload = function(){
            if(hr.readyState == 4 && hr.status == 200){ 
                var text = hr.responseText;
alert(text);
            } else {
                alert(hr.readyState + " " + hr.status);
            }
        }
        hr.send(data);
    }
</script>
<?php

include_once("conn.php");

$fetch_sites = mysqli_query($conn, "SELECT * FROM sites");
while($row = mysqli_fetch_array($fetch_sites)){
    $site_id = $row['id'];
    $site_address = $row['address'];

    $fetch_subs = mysqli_query($conn, "SELECT * FROM subscriptions WHERE site='$site_id'");
    while($row1 = mysqli_fetch_array($fetch_subs)){
        $sub_user = $row1['user'];
        $sub_username = $row1['username'];

        echo "<script>send('$sub_username');</script>";
    }
}
mysqli_close($conn);

?>

它正在尝试将ajax请求发送到托管在具有不同域名的其他服务器上的以下文件。

<?php

header("Content-Control-Allow-Origin: *");

?>
<script>
    function respond(user, posts){
        var data = "user="+user+"&posts="+posts;
        var hr = new XMLHttpRequest();
        hr.open("POST", "http://xenforotest.esy.es/responder.php", true);
        hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        hr.send(data);
    }
</script>
<?php  

$conn = mysqli_connect("host", "user", "password", "db");
if(!$conn){
    echo "this1";
} else {
    echo "this2";
}

$user = $_POST['user'];

$fetch_user = "SELECT message_count FROM xf_user WHERE username='$user'";
$query_user = mysqli_query($conn, $fetch_user);
$row = mysqli_fetch_array($query_user);
    $message_count = $row['message_count'];

echo "<script>respond('$user', '$message_count');</script>";

mysqli_close($conn);

?>

我从第一个文件中得到两个回复说&#34; 2 200&#34;和&#34; 3 200&#34;。所以我的readyState为2,状态为200。

为什么这不起作用?

2 个答案:

答案 0 :(得分:0)

跨域与那里不相关。您的问题是您将数据作为url字符串发送.. POST数据应该在javascript的formdata对象中

答案 1 :(得分:0)

应该是

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

而不是

header("Content-Control-Allow-Origin: *");