如何将 javascript 函数返回的 JSON 保存为变量?

How to save JSON returned in a javascript function as a variable?

我试图在从 api.ipify.org 以 JSON 形式检索客户端 IP 地址后将其保存在变量中。如果我提醒结果但由于某种原因无法将其保存在变量中,我可以获得 IP 以显示。

这个有效:

<script>

function getIP(json) {
    alert(json.ip);
}

</script>
<script src="https://api.ipify.org?format=jsonp&callback=getIP"></script>

但这不起作用:

<script>

var clientIP = ''

function getIP(json) {
    clientIP = json.ip;
    return clientIP;
}

alert(clientIP);

</script>
<script src="https://api.ipify.org?format=jsonp&callback=getIP"></script>

我希望能够将数据存储在一个变量中,这样我就可以将它附加到一个嵌入中,该嵌入将把它添加到它的自动 webhook 中 POST。

<!-- begin video recorder code --><script type="text/javascript">
var IPADDRESSVARIABLE = 'SOME_IP_ADDRESS'
var size = {width:400,height:330};
var flashvars = {qualityurl: "avq/300p.xml",accountHash:"BUNCHOFRANDOMSTUFF", eid:2, showMenu:"true", mrt:120,sis:0,asv:1,mv:0, payload: IPADDRESSVARIABLE};
(function() {var pipe = document.createElement('script'); pipe.type = 'text/javascript'; pipe.async = true;pipe.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 's1.addpipe.com/1.3/pipe.js';var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(pipe, s);})();
</script>
<div id="hdfvr-content"> </div>
<!-- end video recorder code -->

如果我可以将 IP 地址保存为全局变量,那么我可以将它传递到 'flash vars' 的 'payload' 键中。

您的 alert 将无法运行,因为您的代码未同步执行,getIP 直到 您的 alert 后才会被调用] 陈述。您需要在 getIP 函数中触发任何依赖于 clientIP 的功能。这是一个例子:

function getIP(json) {
   var event = new CustomEvent('iploaded', { detail: json.ip });
   document.dispatchEvent(event);
}

document.addEventListener('iploaded', function(event) {
   var IPADDRESSVARIABLE = event.detail;
   var size = {width:400,height:330};
   var flashvars = {qualityurl: "avq/300p.xml",accountHash:"BUNCHOFRANDOMSTUFF", eid:2, showMenu:"true", mrt:120,sis:0,asv:1,mv:0, payload: IPADDRESSVARIABLE};
   (function() {var pipe = document.createElement('script'); pipe.type = 'text/javascript'; pipe.async = true;pipe.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 's1.addpipe.com/1.3/pipe.js';var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(pipe, s);})();
});

// simulate jsonp callback
getIP({ ip: '127.0.0.1' });

另外,在getIP

中不需要return

第二个代码示例不起作用,因为变量仅在回调函数内部被赋予一个值,这意味着同步运行的警报会在 javascript 解释器开始读取和 运行 逐行代码,但 getIP 函数仅在 jsonp 请求 returns 响应时调用。您的第一个代码示例是正确的方法。

正如 Rob 所说,您期望代码同步 运行 但事实并非如此。

这里是对你的代码片段的一个小修改,它可以工作,基本上我已经将警报包装在一个函数中,然后在 getIP 函数完成执行后调用该函数。

<script>

var clientIP = ''

function getIP(json) {
    clientIP = json.ip;
    alertClientIp();
}

function alertClientIp () {
    alert(clientIP);
}

</script>

上面代码段的代码设计有点恶心,如果你只需要使用一次客户端IP,那么就不要把它存储为一个变量,只需将它传递给执行你的函数即可"automated webhook POST"逻辑。

<script>

    function getIP(json) {
        clientIP = json.ip;
        alertClientIp();
    }

    //Accept the client_ip as a param
    function webhookLogic (client_ip) {

       //Execute your logic with the client_ip, 
       //for simplicity I'll stick to your alert.

       alert(client_ip);
    }

    </script>

关于您的编辑

看起来您将两组逻辑放在了两个单独的脚本元素中,您不能将它们合并为一个吗?

<script>

    function getIP(json) {
        clientIP = json.ip;
        alertClientIp();
    }

    //Accept the client_ip as a param
    function webhookLogic (client_ip) {

       //Execute your logic with the client_ip, 
       //for simplicity i'll stick to your alert.

       //Trigger your video wrapper code, unsure if 
       //if this method of execution will break your app...
       videoWrapper(client_ip);
    }

     //Your video code from your latest edit
    function videoWrapper (client_ip) {
        var IPADDRESSVARIABLE = client_ip;
        var size = {width:400,height:330};
        var flashvars = {qualityurl: "avq/300p.xml",accountHash:"BUNCHOFRANDOMSTUFF", eid:2, showMenu:"true", mrt:120,sis:0,asv:1,mv:0, payload: IPADDRESSVARIABLE};
    (function() {var pipe = document.createElement('script'); pipe.type = 'text/javascript'; pipe.async = true;pipe.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 's1.addpipe.com/1.3/pipe.js';var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(pipe, s);})();
   }
    </script>

如果该执行链破坏了您的应用程序,那么我认为您需要重新开始考虑问题的构成,很清楚您想做什么,但您的问题缺少一些元-数据如何这个逻辑都"fits together"。

试试这个:

function getIP(json) {
    return json.ip;
}

var json = { "ip": "111.22.33.44"}
var clientIP = getIP(json);

alert(clientIP);

我找到了解决方法!我将 IP 函数的结果存储到隐藏的 div 中作为容器。然后我在嵌入代码中声明了一个变量并将其设置为 innerHMTL。它可能不是最优雅的,但它完全符合我的要求!

//hidden container to store the client IP address
<div id = 'ipContainer' style='display:none'></div>

//function to retrieve the client IP address
<script>
function getIP(json) {
    document.getElementById('ipContainer').innerHTML = json.ip;
}
</script>

//shortened version of the URL that returns the IP
<script src='http://www.api.ipify.org'><script>


//embed code for the video recorder
<script>
<!-- begin video recorder code --><script type="text/javascript">
var clientIP = document.getElementById('ipContainer').innerHTML;
var size = {width:400,height:330};


//I passed the clientIP variable into the payload element of the flashvars object
var flashvars = {qualityurl: "avq/300p.xml",accountHash:"RANDOM ACCOUNT HASH", eid:2, showMenu:"true", mrt:120,sis:0,asv:1,mv:0, payload:clientIP}; //Here i passed the clientIP which is nor stored as a variable
(function() {var pipe = document.createElement('script'); pipe.type = 'text/javascript'; pipe.async = true;pipe.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 's1.addpipe.com/1.3/pipe.js';var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(pipe, s);})();
</script>
<div id="hdfvr-content"> </div>
<!-- end video recorder code -->