jQuery -连接到一个$。从外部脚本调用ajax

时间:2022-07-02 01:27:23

I'm including a script "foo.js" that I want to modify:

我包含了一个脚本“foo”。我想修改的:

<head>
    <script src="/myPath/foo.js" type="text/javascript"> </script>
</head>

To be able to hook into an ajax call on my main page:

为了能够在我的主页上连接到ajax调用:

$.ajax({
    url: urlPath,
    success: function (data) {
        //hook into here from foo.js somehow??
    }
});

Is there any way to do this solely in foo.js without modifying the main page's script at all? (perhaps hook into a call inside the main script that is filling out/changing content?)

有没有办法只用foo。不修改主页脚本的js ?(也许在主脚本中插入一个正在填写/更改内容的调用?)

Thanks!

谢谢!

2 个解决方案

#1


4  

You can try to use a Global Ajax Event Handlers for listning global events.

您可以尝试使用全局Ajax事件处理程序来列出全局事件。

#2


0  

If your foo.js is wrapped in a closure (if you don't know what this means, just ignore) then you can bind to a namespace and call functions through there.

如果你的foo。js被封装在一个闭包中(如果您不知道这是什么意思,请忽略它),那么您可以绑定到一个名称空间并在那里调用函数。

Otherwise, javascript has a global scope so any scripts imported into your file will have the ability to call functions as long as it is imported in order of dependencies.

否则,javascript具有全局作用域,因此任何导入文件的脚本都可以调用函数,只要它是按照依赖关系导入的。

ie:

即:

foo.js:

foo.js:

function foo(data) {
   // do stuff with data
}

main.html:

main.html:

<head>
   <script src="/myPath/foo.js" type="text/javascript"></script>
   <script type="text/javascript">
       $.ajax({
          url: urlPath,
          success: function(data) {
              foo(data);
          }
       });
   </script>
 </head>

It's important that the embedded script comes AFTER the import so that it can make reference to functions inside foo.js.

在导入之后嵌入的脚本是很重要的,这样它就可以引用foo.js中的函数。

#1


4  

You can try to use a Global Ajax Event Handlers for listning global events.

您可以尝试使用全局Ajax事件处理程序来列出全局事件。

#2


0  

If your foo.js is wrapped in a closure (if you don't know what this means, just ignore) then you can bind to a namespace and call functions through there.

如果你的foo。js被封装在一个闭包中(如果您不知道这是什么意思,请忽略它),那么您可以绑定到一个名称空间并在那里调用函数。

Otherwise, javascript has a global scope so any scripts imported into your file will have the ability to call functions as long as it is imported in order of dependencies.

否则,javascript具有全局作用域,因此任何导入文件的脚本都可以调用函数,只要它是按照依赖关系导入的。

ie:

即:

foo.js:

foo.js:

function foo(data) {
   // do stuff with data
}

main.html:

main.html:

<head>
   <script src="/myPath/foo.js" type="text/javascript"></script>
   <script type="text/javascript">
       $.ajax({
          url: urlPath,
          success: function(data) {
              foo(data);
          }
       });
   </script>
 </head>

It's important that the embedded script comes AFTER the import so that it can make reference to functions inside foo.js.

在导入之后嵌入的脚本是很重要的,这样它就可以引用foo.js中的函数。