简体   繁体   中英

How to get JavaScript variable from ajax loaded page with jQuery?

I'm developing userscript for one webpage (aka browser plugin). I need to update one global Javascript variable (lets call it gVariable (it is an array)) with the one I get with ajax request.

In ajax request I'm requesting for the same page I'm on. But just want to "extract" that one global variable and replace current one with the one downloaded.

This is something I have now (not working).

function LoadNewItemList() {
    $.get(window.location, function (data) {
        var $data = $(data);       
        unsafeWindow.gVariable = data.gVariable; //I'm getting 'undefined'
    });
}

JS test: http://jsfiddle.net/ywVKT/15/

Looking at your fiddle, there are mainly 4 tags. ie "title" , "link" , "ul" , "script". That's why you need to use index as 3, since the script tag contains the variable name and value. Try this and it would work.

$('#variableHere').text(data2[3].innerText);

it will return you following o/p: var gVariable = 0; gVariable = 5 Now you can use regex/substring function to extract the vairable name and value..

I found solution:

unsafeWindow.gVariable = 0;
var $script = $data.filter('script:contains("var gVariable")').first();
eval($script.text());
unsafeWindow.gVariable = gVariable;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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