skip to Main Content

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


  1. You can get the value if you store the values in the form of JSON (JavaScript Object Notation)

    i.e.,

    <script>
    {
    var1: "Something",
    var2: "Another Thing",
    var3: "",
    }
    </script>
    

    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.

    Login or Signup to reply.
  2. I think you just want the value of var2, right? If so, why not use Regex?

    data.match(/var2 = "(.*)"/)[1]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search