简体   繁体   English

jQuery Ajax响应中定义的调用函数

[英]Calling function defined in jquery ajax response

I am doing an ajax request to a php page ('test.php') inside of test.php is 我正在对test.php内的php页面('test.php')进行ajax请求是

<script type="text/javascript">
 function test() {
alert('test');
}
</script>

<div id="abc">some normal content too</div>

now this function is unique to each page load, ie it is generated via php to do different things 现在,此功能对于每个页面加载都是唯一的,即它是通过php生成的,用于执行不同的操作

so, my question is how do i call that function test(); 因此,我的问题是如何调用该函数test();。

as jquery thinks the response is just text so it does not eval it 正如jquery认为响应只是文本,所以它不会评估它

jquery has datatypes for the return jQuery具有返回的数据类型

one is script the other is html 一个是脚本,另一个是html

however it does not seem to have mixed. 但是它似乎并没有混合在一起。

how can i fix this? 我怎样才能解决这个问题?

The jQuery .load() function will evaluate <script> tags in the response content, but only if your call to .load() does not involve a selector to pull part of the response out before it's inserted in the DOM. jQuery的.load()函数评估<script>的响应内容的标签,但只有当你调用.load() 涉及选择退出之前,它插在DOM响应的一部分。

Thus, this call: 因此,此调用:

 $('#myContainer').load("/some/url", function() { /* ... */ });

will cause any script content to be run, but this: 将导致运行任何脚本内容,但这:

 $('#myContainer').load("/some/url #stuffIWant", function() { /* ... */ });

will not. 将不会。 I don't know why it works that way, but it does. 我不知道为什么会这样,但确实如此。

If you're loading it the first way, understand that you won't be able to use anything defined as a global function (or a global anything) until the loading has completed. 如果您以第一方式进行加载,请理解,直到加载完成,您才能使用定义为全局函数的任何内容(或全局的任何内容)。 Thus: 从而:

$('#someplace').load(url, function() { } );
newGlobalFunction("hi");

won't work because "newGlobalFunction" won't be defined until the asynchronous request completes. 将无法工作,因为在异步请求完成之前不会定义“ newGlobalFunction”。 Thus, this should work: 因此,这应该起作用:

$('#someplace').load(url, function() {
  newGlobalFunction("hi");
});

If your ajax result is nothing but that script content, you could also consider not wrapping it in <script> tags and just eval it yourself! 如果您的ajax结果只不过是脚本内容,那么您也可以考虑不将其包装在<script>标记中,而自己进行评估!

Have you tried loading it as an external file? 您是否尝试过将其作为外部文件加载? The external file could ofcource be a php page as well generation JS code. 外部文件可以是php页面,也可以是生成JS代码。

br, br
Paul 保罗

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

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