繁体   English   中英

从HTTP请求执行JavaScript函数

[英]Execute a javascript function from HTTP Request

嗨,我正在尝试获取将从HTTP Get Request获得的功能。 但是我无法使脚本运行

我的代码是:

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    <script type="text/javascript">

        window.launch = function(url, has_credits) {
            if (has_credits != "True"){
                if (!confirm(con_str)){
                    window.close();
                }
            }
            document.getElementById("waiting_msg").innerHTML = "Loading..."
            location.href = url;
        };

        var xmlHttp = new XMLHttpRequest();
        theUrl = 'http://127.0.0.1:8000/game/launch/?provider=XXX&game=7bal_tie&token=50c63444b85cdadf5e4b9285c2be5444&jsonp=launch'
        xmlHttp.open( "GET", theUrl, true );
        xmlHttp.send( null );
        //
            // The script that will trigger  the function 
        //
    </script>
</body>
</html>

请求的返回是

launch("http://my-url.com","False");

哪个应该将我重定向到上述网址。 我希望javascript具有内置功能,可以像这样轻松运行它

func(xmlHttp.response);

然后将触发该功能,但我找不到任何内容,并且没有为我锻炼

eval应该可以,但是除了原型之外,这对于所有其他事情来说都是一个坏主意。 您尚未设置responseType但是我想您想要的是responseText而不是response 我不确定会是什么类型的response但是它可能是缓冲区或类似的东西,这不是您想要的。

您可以执行以下操作:

function reqListener () {
  if (xmlHttp.status !== 200) return;
  eval(this.responseText);
}

xmlHttp.addEventListener("load", reqListener);

但是,再次使用eval是一个坏主意。 假设您将API响应更改为:

{
  "func": "launch",
  "params": ["http://my-url.com", "False"]
}

然后,您可以执行以下操作:

function reqListener () {
  if (xmlHttp.status !== 200) return;
  var respObj = JSON.parse(this.responseText);
  window[respObj.func].apply(window, respObj.params);
}

xmlHttp.addEventListener("load", reqListener);

这仍然不是理想的,因为它可以用于在window对象上执行任意代码,但是比它直接使用eval更好,因为它限制了漏洞的范围。

这个问题的真正答案是,您不应该对远程执行代码的可能性保持开放。 因此,请勿在生产中使用此代码,而应重新设计API。

暂无
暂无

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

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