将jQuery转换为等效的JavaScript代码

时间:2015-01-13 20:00:59

标签: javascript jquery ajax

我知道如何使用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无法正常工作,但失败了。我使用不同的域,因为我们发送数据的站点托管在另一台服务器上。

3 个答案:

答案 0 :(得分:2)

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

为了确保您的网站加载了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'];
} 

答案 1 :(得分:1)

令人讨厌的部分是您需要执行跨域POST来发送数据。这种称为跨源资源共享(CORS)的W3C标准。查看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>

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

答案 2 :(得分:0)

$.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);