我知道如何很好地使用jQuery,但我不太了解纯JavaScript。
这是我的jQuery代码:
$(document).ready(function() {
$.get('http://jsonip.com/', function(r){
var ip_address = r.ip;
my_function(ip_address);
});
function my_function(ip_address){
var url = "Url_to my server hosted on a different domain";
var data = {number:"1286", ip: ip_address};
$.ajax({
url: url,
type: "POST",
dataType: 'json',
crossDomain: true,
data: {data: data},
success: function (data) {console.log(JSON.stringify(data));},
error: function (xhr, error) {console.log("There was an error and data was not posted.");}});}
});
它的作用:将其粘贴到任何网站中,然后选择任何访问者的IP地址,并将其作为JSON作为变量数据发送到我的服务器。
问题:由于jQuery依赖关系,代码在某些站点中可以正常运行,但并非在所有站点中都可以。我想删除它并使用纯JavaScript。
我得到了很好的答案,但CORS无法正常工作,使它们失败了。我正在使用不同的域,因为我们要向其发送数据的站点托管在另一台服务器上。
就像我上面的评论中提到的那样,您不需要第一个ajax请求,因为您可以从AJAX请求的请求标头(下面的PHP示例)中获取此信息。
为了确保您的网站已加载jQuery,您可以在脚本中运行检查并动态加载它。使用此答案中的一些代码。参见以下示例:
// Anonymous "self-invoking" function
(function() {
// Load the script
var script = document.createElement("SCRIPT");
script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js';
script.type = 'text/javascript';
document.getElementsByTagName("head")[0].appendChild(script);
// Poll for jQuery to come into existance
var checkReady = function(callback) {
if (window.jQuery) {
callback(jQuery);
}
else {
window.setTimeout(function() { checkReady(callback); }, 100);
}
};
// Start polling...
checkReady(function($) {
var url = "Url_to my server hosted on a different domain";
var data = {number:"1286", ip: ip_address};
$.ajax({
url: url,
type: "POST",
dataType: 'json',
crossDomain: true,
data: {data: data},
success: function (data) {console.log(JSON.stringify(data));},
error: function (xhr, error) {console.log("There was an error and data was not posted.");
});
});
})();
要从ajax请求中获取IP地址,请执行以下操作:(PHP)源
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$ip = $_SERVER['REMOTE_ADDR'];
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句