将 jQuery 转换为 JavaScript 等效代码

Convert jQuery to JavaScript code equivalent

我知道怎么用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 没有工作,他们失败了。我正在使用不同的域,因为我们要向其发送数据的站点托管在另一台服务器上。

$.ready(function...) 替换为 document.addEventListener('DOMContentLoaded', function..., false)

$.ajax替换为XMLHttpRequest:

var xhr = new XMLHttpRequest();

//var data = {number:"1286", ip: ip_address};
var data = new FormData();
data.append("number", "1286");
data.append("ip", ip_address); // As stated by Scriptable in the question comments, your server should be able to get it from the request headers.

xhr.onload = function() { console.log(JSON.stringify(this.response)); };

xhr.onerror = function() { console.log("There was an error and data was not posted.") };

xhr.open("POST", "URL to your server");
xhr.send(data);

正如我在上面的评论中提到的,您不需要第一个 ajax 请求,因为您可以从 headers 请求(下面的 PHP 示例)中获取此信息 AJAX请求。

为确保您的网站已 jQuery 加载,您可以 运行 检查您的脚本并动态加载它。使用此 answer 中的一些代码。请参阅下面的示例:

// 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) Source

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'];
} 

烦人的部分是您需要跨域 POST 才能发送数据。为此有一个 W3C 标准,称为跨源资源共享 (CORS)。查看 this tutorial 了解更多信息。

您需要将它放在页面底部。不同的浏览器处理就绪状态变化事件的方式不同,所以我们尽量避免它们。

<script>
    // Once the JSONP script loads, it will call this function with its payload.
    function getip(ipJson) {
        var method = 'POST';
        var url = 'URL of your server';

        // The XMLHTTPRequest is the standard way to do AJAX. Try to use CORS.
        var xhr = new XMLHttpRequest();

        if ("withCredentials" in xhr) {
            // XHR for Chrome/Firefox/Opera/Safari.
            xhr.open(method, url, true);
        } else if (typeof XDomainRequest != "undefined") {
            // XDomainRequest for IE.
            xhr = new XDomainRequest();
            xhr.open(method, url);
        }

        // Create your request body. It has to be form encoded. I'm not sure
        // where you get `number` from, so I've hard-coded it.
        xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
        xhr.send('number=1286&ip=' + ipJson.ip);
    }
</script>

<!-- Get the IP using JSONP so we can skip implementing that. -->
<script type="application/javascript" src="http://www.telize.com/jsonip?callback=getip"></script>

这可能只适用于现代浏览器,但它应该适用于大多数现代浏览器。