AJAX Post JQuery不支持CORS

时间:2014-11-20 11:37:10

标签: javascript php jquery ajax

对不起, 我尝试抓住我的客人并使用javascript ajax post保存它。

它是不同的主机(在js和php服务器之间)。 这是javascript:

<script language="Javascript" src="http://www.codehelper.io/api/ips/?js"></script>
<script language="Javascript">
    var myip = codehelper_ip.IP;
    var mycountry = codehelper_ip.Country;
    var myurl = document.URL;
    $.ajax({
        type: 'POST',
        url: 'http://myhost.com/guest-catcher/guest-post.php',
        crossDomain: true,
        data: '{"ip":"'+myip+'", "country":"'+mycountry+'", "page":"'+myurl+'"}',
        dataType: 'json',
        success: function(responseData, textStatus, jqXHR) {
            alert("success");
        },
        error: function (xhr, status, error) {
            alert(xhr.responseText);
        }
    });
</script> 

服务器端代码:

<?php

$ip = "";
if ($_POST['ip']) {
    $ip = $_POST['ip'];
}
$country = "";
if ($_POST['country']) {
    $country = $_POST['country'];
}
$page = "";
if ($_POST['page']) {
    $page = $_POST['page'];
}

//Start Save DB
$conn = new mysqli($db_host, $db_user, $db_pass, $db_name);
$sql = "INSERT INTO blog_guest (ip_address, country, page) VALUES ('" . $ip . "', '" . $country . "','" . $page . "')";
if ($ip != "" || $country != "" || $page!= "") {
    if ($conn->query($sql) === TRUE) {
    } else {
        echo '<script>alert("' . $conn->error . '")</script>';
    }
}
$conn->close();
//End Save DB

浏览器控制台出错:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at myhost.com/guest-catcher/guest-post.php. This can be fixed by moving the resource to the same domain or enabling CORS.

4 个答案:

答案 0 :(得分:0)

您的data选项错误。它应该是Javascript对象,而不是JSON字符串。

data: {"ip": myip, "country": mycountry, "page": myurl},

此外,您的服务器脚本不会返回JSON,因此您不应该:

dataType: 'json',

答案 1 :(得分:0)

您必须按以下方式转换数据:data=JSON.stringify(your data);

示例:

var d = {...}; # your dict.
$.ajax({                      
    type:'post',
    contentType:'application/json',
    url:type url here,
    dataType:'json',
    data:JSON.stringify(d),
    beforeSend:function(){

    },
    success:function(){

    }
});

答案 2 :(得分:0)

请用此替换ajax代码并检查。

$.ajax({
    type: 'POST',
    url: 'http://myhost.com/guest-catcher/guest-post.php',
    crossDomain: true,
    data: 'ip=' + myip + '&country=' + mycountry + '&page=' + myurl,
    success: function(responseData, textStatus, jqXHR) {
        alert("success");
    },
    error: function (xhr, status, error) {
        alert(xhr.responseText);
    }
});

答案 3 :(得分:-2)

$.ajax({
    type: "POST",
    url: "some.php",
    data: { name: "John", location: "Boston" } // or  data: "name=" + value  + "location=" + value
})