简体   繁体   English

如何使用jQuery从Ajax加载页面获取JavaScript变量?

[英]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. 我需要用ajax请求得到的一个全局Java变量(称为gVariable(它是一个数组))进行更新。

In ajax request I'm requesting for the same page I'm on. 在ajax请求中,我请求的页面是同一页面。 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/ JS测试: http//jsfiddle.net/ywVKT/15/

Looking at your fiddle, there are mainly 4 tags. 看您的小提琴,主要有4个标签。 ie "title" , "link" , "ul" , "script". 即“标题”,“链接”,“ ul”,“脚本”。 That's why you need to use index as 3, since the script tag contains the variable name and value. 这就是为什么您需要将index用作3的原因,因为script标记包含变量名和值。 Try this and it would work. 试试这个,它会起作用。

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

it will return you following o/p: var gVariable = 0; 它将按照o / p返回: var gV​​ariable = 0; gVariable = 5 Now you can use regex/substring function to extract the vairable name and value.. gVariable = 5现在,您可以使用regex / substring函数来提取可变名称和值。

I found solution: 我找到了解决方案:

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

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

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