简体   繁体   English

将jQuery转换为等效的JavaScript代码

[英]Convert jQuery to JavaScript code equivalent

I know how to use jQuery well, but I don't know so much pure JavaScript. 我知道如何使用jQuery,但我不知道这么多纯JavaScript。

This is my jQuery code: 这是我的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.");}});}
});

What it does: it is pasted in any website, then it picks any visitors ip address and send that as JSON to my server as variable data. 它的作用:它被粘贴在任何网站上,然后它选择任何访问者的IP地址,并将其作为JSON发送到我的服务器作为可变数据。

Problem: the code is working perfectly okay in some sites but not all the sites due to jQuery dependency. 问题:由于jQuery依赖性,代码在某些站点中工作得很好,但不是所有站点。 And I want to remove this and use pure JavaScript. 我想删除它并使用纯JavaScript。

I am getting great answers but CORS is not working, there failing them. 我得到了很好的答案,但CORS无法正常工作,失败了。 I am using different domains since the site we are sending data to is hosted on another server. 我使用不同的域,因为我们发送数据的站点托管在另一台服务器上。

As mentioned in my commment above, you do not need the first ajax request as you can get this information from the request headers (PHP Example below) from your AJAX request. 正如我在上面的提交中所提到的,您不需要第一个ajax请求,因为您可以从AJAX请求中的请求标头(下面的PHP示例)中获取此信息。

To make sure that your website(s) have jQuery loaded you can run a check in your script and load it in dynamically. 为了确保您的网站加载了jQuery,您可以在脚本中运行检查并动态加载它。 Using some code from this answer . 使用此答案中的一些代码。 See below for an example: 请参阅下面的示例:

// 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.");
        });
    });
})();

To get the IP Address from your ajax request: (PHP) Source 从您的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'];
} 

The annoying part is that you need to do a cross-domain POST to send your data. 令人讨厌的部分是您需要执行跨域POST来发送数据。 There's a W3C standard for this called Cross-Origin Resource Sharing (CORS). 这种称为跨源资源共享(CORS)的W3C标准。 Check out this tutorial for more info. 查看本教程以获取更多信息。

You'll want to put this at the bottom of the page. 你想把它放在页面的底部。 Different browsers handle ready state change events differently, so let's just avoid them. 不同的浏览器以不同的方式处理就绪状态更改事件,所以让我们避免它们。

<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>

This probably only works in modern browsers, but it should work in most modern browsers. 这可能仅适用于现代浏览器,但它应该适用于大多数现代浏览器。

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

Replace $.ajax with XMLHttpRequest : XMLHttpRequest替换$.ajax

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM