我喜欢做一个基于访问者状态/地区的广告。还可以显示基于访问者国家的语言。
我正试图从这个网站获得数据,并在(仅显示输出)中工作良好:
jQuery.ajax( {
url: '//freegeoip.net/json/',
type: 'POST',
dataType: 'jsonp',
success: function(location) {
// example where I update content on the page.
jQuery('#city').html(location.city);
jQuery('#region-code').html(location.region_code);
jQuery('#region-name').html(location.region_name);
jQuery('#areacode').html(location.areacode);
jQuery('#ip').html(location.ip);
jQuery('#zipcode').html(location.zipcode);
jQuery('#longitude').html(location.longitude);
jQuery('#latitude').html(location.latitude);
jQuery('#country-name').html(location.country_name);
jQuery('#country-code').html(location.country_code);
}
} );
当然,这将给出浏览器上的访问者状态数据:
<div id="region-name"></div>
问题:
- 我如何得到id输出保存在php字符串。
- 我想让它使用PDO准备语句数据库。
我试图通过以下方式来保存它:
$state='<div id="region-name"></div>';
$pages->testsavestate($state); // save to database PDO
public function testsavestate($state) {
$ses_id = session_id();
$country='mycountry';
$query = $this->db->prepare("INSERT INTO `visitors`(`session`, `country`, `state`) VALUES
(?,?,?)");
$query->bindValue(1, $ses_id);
$query->bindValue(2, $country);
$query->bindValue(3, $state);
try{
$query->execute();
}catch(PDOException $e){
die($e->getMessage());
}
}
不保存状态结果,只保存标签上面的结果。
谢谢
为了使该数据从您的第一个AJAX调用传递到获取位置值。您还可以在此基础上对PHP处理调用另一个ajax。考虑这个例子:
jQuery.ajax( {
url: '//freegeoip.net/json/',
type: 'POST',
dataType: 'jsonp',
success: function(location) {
jQuery('#city').html(location.city);
jQuery('#region-code').html(location.region_code);
jQuery('#region-name').html(location.region_name);
jQuery('#areacode').html(location.areacode);
jQuery('#ip').html(location.ip);
jQuery('#zipcode').html(location.zipcode);
jQuery('#longitude').html(location.longitude);
jQuery('#latitude').html(location.latitude);
jQuery('#country-name').html(location.country_name);
jQuery('#country-code').html(location.country_code);
// after your .html() below
// after your successful ajax outside, call your php file
var country = location.country_name;
var state = location.region_name;
// call your php file
jQuery.ajax({
url: 'index.php', // <-- name of the php file that will handle such request
type: 'POST',
dataType: 'JSON',
data: { country: country, state: state },
success: function(response) {
alert(response);
}
});
}
});
然后在php文件中处理
if(isset($_POST['save'])) {
$country = $_POST['country'];
$state = $_POST['state'];
$ses_id = session_id();
$query = $this->db->prepare("INSERT INTO `visitors`(`session`, `country`, `state`) VALUES (?,?,?)");
$query->bindValue(1, $ses_id);
$query->bindValue(2, $country);
$query->bindValue(3, $state);
try {
$query->execute();
if($query->rowCount() > 0) {
echo "Save complete!";
exit;
}
} catch(PDOException $e){
die($e->getMessage());
}
}