运行 AJAX 调用的 javascript 代码

发布于 2025-01-05 08:19:53 字数 489 浏览 1 评论 0原文

我的网站使用pushState来加载页面。我有一个问题,我想在其中一个页面上使用 javascript,但不能,因为它使用 AJAX 加载所有内容。那我该怎么办?有人告诉我一些有关“parseScript”的信息,但我找不到足够的信息。

--示例--

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

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

什么也没有发生。

--编辑--

如果我打开 Google Chrome 的调试器: “未捕获的引用错误:go 未定义” 和 <脚本>标签在哪里找不到

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.

--Example--

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.

--Edit--

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

好倦 2025-01-12 08:19:53

浏览器似乎无法解析通过 targetElement.innerHTML 添加到文档的

最好的解决方案是使用像 jQuery 这样经过良好测试的框架来解决此类问题。他们已经弄清楚如何安全、正确地将脚本注入 DOM 中。除非您绝对无法为库腾出带宽,否则重新发明轮子是没有意义的。


解决此问题的一种方法是在 Ajax 响应中将 JavaScript 与 HTML 分开,方法是发出两个请求(可能较慢)或在 JSON 对象中构建 JavaScript 和 HTML(可能更难维护)。

下面是一个示例:

<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 如下所示:

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

如果您选择此路线,则必须:

  • 命名您的函数: MyApp.foo = function (){ .. };,或
  • 显式地将函数添加到全局命名空间:window.foo = function (){ ... };

这是因为 eval 在当前作用域中执行,因此您的函数定义继承该作用域并且不会全局可用。在我的示例中,我选择了后一个选项,因为它只是一个简单的示例,但您应该知道为什么这是必要的。

请务必阅读JavaScript 的 eval() 什么时候不是邪恶的? 如果您决定自己实现这一点。

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.

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.


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).

Here's an example:

<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>

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:

  • 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.

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

桃气十足 2025-01-12 08:19:53

我认为更详细地了解如何进行 Ajax 调用和加载内容会很有帮助。也就是说,有一些值得注意的事情:

  • javascript:void() 的语法无效。它应该是 javascript:void(0)。就此而言,在锚标记的 href 上使用 javascript:void() 通常是不好的做法。有些浏览器不支持。如果必须使用标签,请将 href 设置为 # 并添加“return false;”到点击事件。
  • 无论如何,在这种情况下您应该使用按钮标签而不是 a 标签。
  • 鉴于您提供的内容,它应该可以工作(除了 void() 的语法错误)

I think it would be helpful to have a little more detail as to how the Ajax call is made and the content is loaded. That said, a few things of note:

  • the syntax for javascript:void() is invalid. It should be javascript:void(0). For that matter, using javascript:void() on the href of an anchor tag is generally bad practice. Some browsers do not support it. If you must use an tag, set the href to # and add "return false;" to the click event.
  • you should use a button tag instead of the a tag in this case anyway.
  • given what you have provided, it should work (aside from the syntax error with void())
风渺 2025-01-12 08:19:53

如果我要这样做,我会使用 jquery 的 load 调用。
它负责放置 ajax 调用,并解析脚本/无脚本元素的标签。

如果您不想使用 jquery,我建议您上网查找 jquery load 方法的作用,并为您的 ajax 调用实现与事件处理程序相同的方法。

If I were to do this I would use jquery's load call.
That takes care of putting an ajax call ,and parsing tags for script/no-script elements.

IF you dont wanna use jquery, I would suggest you go online and find what the jquery load method does and implement the same as an event handler for your ajax call.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文