I’m stuck with a problem you might resolve.
There is a HTML page with differents informations, in this page there is also some JS variables.
<div class="div1">
<div class="div2"></div>
</div>
<script type="text/javascript">
var var1 = "Something";
var var2 = "Another thing";
var var3 = "";
</script>
Now when I call this page in ajax :
$.ajax({
type: 'GET',
url: 'mypage.php',
success: function(data) {
// Trying to get the var value
}
});
I wish to get the var and what it contains. I can write this to get HTML part :
console.log($(data).find(".div1").html());
or
console.log($(data).find("script").html()); // To get the JS part
But I just want only one var (like var2), not the whole javascript :/
I hope i’m clear, sorry for my english, I do my best.
Thank you
2
Answers
You can get the value if you store the values in the form of JSON (JavaScript Object Notation)
i.e.,
and at last,
console.log($(data).find("script").html().var2);
for the value of var2.
But, this is not the best way to do it!
You can either store all the variables and code in only one
<script>
tag or use an external *.js file which contains your code or use the browser localStorage, sessionStorage to do it. Using cookies is also not recommended although it will work.I think you just want the value of var2, right? If so, why not use Regex?