AJAX Post JQuery does not working CORS

AJAX Post JQuery does not working CORS

本文关键字:working CORS not does Post JQuery AJAX      更新时间:2023-09-26

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

它是不同的主机(在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.

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

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

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

dataType: 'json',

您必须像这样转换数据: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(){
    }
});

请将 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);
    }
});
$.ajax({
    type: "POST",
    url: "some.php",
    data: { name: "John", location: "Boston" } // or  data: "name=" + value  + "location=" + value
})