accessing JS variable in HTML+JS string
I have a string containing some HTML. Within that HTML there is a bit of <script>
, within which there is a variable defined. How do I access that variable?
e.g. I make XHR request, which returns something like:
<html>
<head>
<!-- irrelevant cod开发者_高级运维e -->
<head>
<body>
<!-- irrelevant code -->
<script>var bar = {car: tar};</script>
<!-- irrelevant code -->
</body>
</html>
And I need to access the bar
variable. Basically what's happening, I have access to a script dom.ltd/foo.js
, which makes XHR request to dom.ltd/bar.php
which returns HTML+JS.
JS holds JSON string which is generated on server side. Unfortunately, I am not allowed to touch the PHP, therefore I need to parse it out of the returned string.
The only way to accomplish that is to cut the string and eval()
anything which is written between the <script>
tags. I don't want to raise my finger and tell you that this can be a dangerous thing (it can be if the source is not trusted), so here is the deal:
var recv = "<html><head><body><script>var bar = {car: 'tar'};</script></body></html>",
code = /<script>(.*?)<\/script>/.exec(recv)[ 1 ];
eval(code);
console.log( bar ); // Object { car="tar" }
I would describe the above as horrible code, since parsing HTML with regexp is a bad thing, eval
is a bad thing and transfering HTML to the client is a bad thing.
However, in a very small sandbox environment this would work. If there is no way you can change the server behavior to transmit JSON-data instead of HTML, you really need to make sure that there can't be any malicous code in there.
if you know the bar variable is always an array in that format I would go for something like this:
var bar = response.substring(indexOf("{"), indexOf("}"));
精彩评论