AJAX Post JQuery does not working CORS
AJAX Post JQuery does not working CORS
对不起,我尝试抓住我的客人并使用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
})
相关文章:
- $rootScope not working
- CORS-重定向到第二个GET正在接收的页面
- jQuery document.ready not working
- node.js请求数据事件未在CORS ajax调用中触发
- Javascript getElementsByTagName not working?
- 带有凭据的角度文件上载(CORS)不起作用
- 与域在同一台计算机上运行的NODEJS服务器的CORS错误
- SmartGWT数据源和CORS
- JQuery.val( ) not working
- CORS-服务器端cookie没有保存在chrome浏览器上
- Tomcat websocket is not working
- Javascript JSON.parse not working
- CORS:否'访问控制允许来源'header-但是php设置头文件
- NodeJS Multer is not working
- Regex not working
- CORS:访问控制允许原点不等于提供的原点
- Ember run.debounce not working
- jQuery Ajax cors IE10 not working
- AJAX Post JQuery does not working CORS
- Ajax Jquery CORS not working