运行的JavaScript code称为AJAX

运行的JavaScript code称为AJAX

问题描述:

我的网站使用pushState加载页面。我有一个问题,我想使用JavaScript的网页之一,但不能因为它加载一切与AJAX。所以,我该怎么办?有人告诉我一些有关parseScript但我不能找到它足够的信息。

My site uses pushState to load pages. I have one issue, I want to use javascript on one of the pages but can't because it loads everything with AJAX. So what do I do? I've been told something about "parseScript" but I can't find enough information on it.

- 示例 -

我加载使用AJAX 在我的网页我有这样的脚本:

I load using AJAX On my page I have this script:

<script type="text/javascript">
        function go(){
            alert('1');
        }
    </script>
<a href="javascript:void();" onClick="go();">GO!!!</a>

什么也没有发生。

Nothing happens.

- 编辑 -

如果我打开谷歌Chrome浏览器的调试器: 未捕获的Ref​​erenceError:走的是未定义 和&lt; script>标记是可以找到任何地方

If I open up Google Chrome's debugger: "Uncaught ReferenceError: go is not defined" And the <script> tag is no where to be found

浏览器似乎不解析&LT;脚本&GT; 就是通过添加到文档元素含量 targetElement.innerHTML 。这可能是你正在运行成什么样。

Browsers don't seem to parse <script> element content that's added to the document via targetElement.innerHTML. That's probably what you're running into.

最好的解决方案是使用像jQuery一个良好的测试框架,为解决这样的问题。他们已经找到了如何安全正确地注入脚本到DOM。有没有感觉重新发明*,除非你绝对不能饶恕的带宽库。

The best solution is to use a well-tested framework like jQuery for solving problems like this. They've already figured out how to safely and correctly inject scripts into the DOM. There's no sense re-inventing the wheel unless you absolutely can't spare the bandwidth for the library.

您可能会解决这个问题的方法之一是从Ajax响应的HTML分离的JavaScript,通过发出两个请求(可能慢),或通过一个JSON对象(很可能难以维持)在构建您的JavaScript和HTML。

One way you might fix this is by separating the JavaScript from the HTML in the Ajax response, either by issuing two requests (probably slower) or by structuring your JavaScript and HTML within a JSON object (probably harder to maintain).

下面是一个例子:

<script>

function load_content(){
  var req = new XMLHttpRequest();
  req.open("GET", "ajax.json", true);
  req.onreadystatechange = function (e){
    if (req.readyState === 4){
      if (req.status === 200){

        // these three lines inject your JavaScript and
        // HTML content into the DOM
        var json = JSON.parse(req.responseText);
        document.getElementById("target").innerHTML = json.html;
        eval(json.js);
      } else {
        console.log("Error", req.statusText);
      }
    }
  };
  req.send(null);
}

</script>

<a href="#" onclick="load_content()">Load more stuff</a>
<div id="target"></div>

文件 ajax.json 在服务器上看起来是这样的:

The document ajax.json on the server looks like this:

{
  "js": "window.bar = function (){ console.log(\"bar\"); return false; }",
  "html": "<p><a href=\"#\" onclick=\"bar();\">Log a message</a></p>"
}

如果你选择这条路,你必须:

If you choose this route, you must either:

  • 命名空间的功能: MyApp.foo =功能(){...};
  • 明确地添加功能全局命名空间: window.foo =功能(){...};
  • namespace your functions: MyApp.foo = function (){ ... };, or
  • explicitly add your functions to the global namespace: window.foo = function (){ ... };.

这是因为评估在当前范围内执行,所以你的函数定义继承范围并不会全局可用。在我的例子中,我选择了后者的选择,因为它只是一个简单的例子,但是你应该知道为什么这是必要的。

This is because eval executes in the current scope, so your function definitions inherit that scope and won't be globally available. In my example, I chose the latter option since it's just a trivial example, but you should be aware of why this is necessary.

请务必阅读当是JavaScript的的eval()不是罪恶? 如果你决定自己实现。

Please make sure to read When is JavaScript's eval() not evil? if you decide to implement this yourself.