AJAX Post JQuery无法正常工作 [英] AJAX Post JQuery does not working CORS

查看:83
本文介绍了AJAX Post JQuery无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不好意思,我试图抓住我的客人,并使用javascript ajax post保存它..

Excuse me, I try to catch my guest and save it using javascript ajax post..

这是另一台主机(介于js和php服务器之间).这是javascript:

It is different host (between the js and php server). This is the 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

浏览器控制台出现错误:

Error at Browser console:

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.

推荐答案

请以此替换ajax代码并进行检查.

Please replace the ajax code with this and check.

$.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 Post JQuery无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆