簡體   English   中英

將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無法正常工作,失敗了。 我使用不同的域,因為我們發送數據的站點托管在另一台服務器上。

正如我在上面的提交中所提到的,您不需要第一個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'];
} 

令人討厭的部分是您需要執行跨域POST來發送數據。 這種稱為跨源資源共享(CORS)的W3C標准。 查看本教程以獲取更多信息。

你想把它放在頁面的底部。 不同的瀏覽器以不同的方式處理就緒狀態更改事件,所以讓我們避免它們。

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

這可能僅適用於現代瀏覽器,但它應該適用於大多數現代瀏覽器。

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

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