简体   繁体   English

为什么不是我的<script> tag work from php file? (jQuery involved here too)

[英]Why doesn't my <script> tag work from php file? (jQuery involved here too)

Here is what I am trying to accomplish. 这是我想要完成的。 I have a form that uses jQuery to make an AJAX call to a PHP file. 我有一个使用jQuery对PHP文件进行AJAX调用的表单。 The PHP file interacts with a database, and then creates the page content to return as the AJAX response; PHP文件与数据库交互,然后创建页面内容以作为AJAX响应返回; ie this page content is written to a new window in the success function for the $.ajax call. 即,此页面内容将写入$.ajax调用的成功函数中的新窗口。 As part of the page content returned by the PHP file, I have a straightforward HTML script tag that has a JavaScript file. 作为PHP文件返回的页面内容的一部分,我有一个简单的HTML脚本标记,其中包含一个JavaScript文件。 Specifically: 特别:

<script type="text/javascript" src="pageControl.js"></script>

This is not echoed in the php (although I have tried that), it is just html. 这不是在PHP中回应(虽然我已经尝试过),它只是html。 The pageControl.js is in the same directory as my php file that generates the content. pageControl.js与生成内容的php文件位于同一目录中。

No matter what I try, I can't seem to get the pageControl.js file included or working in the resulting new window created in response to success in the AJAX call. 无论我尝试什么,我似乎都无法获得包含的pageControl.js文件,或者在为响应AJAX调用成功而创建的新窗口中工作。 I end up with errors like "Object expected" or variable not defined, leading me to believe the file is not getting included. 我最终得到像“预期的对象”或未定义的变量之类的错误,这让我相信文件没有包含在内。 If I copy the JavaScript directly into the PHPfile, rather than using the script tag with src, I can get it working. 如果我将JavaScript直接复制到PHP文件中,而不是将脚本标记与src一起使用,我可以使它工作。

Is there something I am missing here about scope resolution between calling file, php, and the jQuery AJAX? 这里有关于调用文件,php和jQuery AJAX之间的范围解析的东西吗? I am going to want to include javascript files this way in the future and would like to understand what I am doing wrong. 我将来希望以这种方式包含javascript文件,并希望了解我做错了什么。


Hello again: 再次问好:

I have worked away at this issue, and still no luck. 我已经解决了这个问题,但仍然没有运气。 I am going to try and clarify what I am doing, and maybe that will bring something to mind. 我将尝试澄清我在做什么,也许这会带来一些想法。 I am including some code as requested to help clarify things a bit. 我按要求包含了一些代码,以帮助澄清一些事情。

Here is the sequence: 这是序列:

  1. User selects some options, and clicks submit button on form. 用户选择一些选项,然后单击表单上的提交按钮。
  2. The form button click is handled by jQuery code that looks like this: 单击表单按钮由jQuery代码处理,如下所示:

     $(document).ready(function() { $("#runReport").click(function() { var report = $("#report").val(); var program = $("#program").val(); var session = $("#session").val(); var students = $("#students").val(); var dataString = 'report=' +report+ '&program=' +program+ '&session=' +session+ '&students=' +students; $.ajax({ type: "POST", url: "process_report_request.php", cache: false, data: dataString, success: function(pageContent) { if (pageContent) { $("#result_msg").addClass("successMsg") .text("Report created."); var windowFeatures = "width=800,menubar=yes,scrollbars=1,resizable=1,status=yes"; // open a new report window var reportWindow = window.open("", "newReportWindow", windowFeatures); // add the report data itself returned from the AJAX call reportWindow.document.write(pageContent); reportWindow.document.close(); } else { $("#result_msg").addClass("failedMsg") .text("Report creation failed."); } } }); // end ajax call // return false from click function to prevent normal submit handling return false; }); // end click call }); // end ready call 

This code performs an AJAX call to a PHP file ( process_report_request.php ) that creates the page content for the new window. 此代码对PHP文件( process_report_request.php )执行AJAX调用,该文件为新窗口创建页面内容。 This content is taken from a database and HTML. 此内容取自数据库和HTML。 In the PHP file I want to include another javascript file in the head with javascript used in the new window. 在PHP文件中,我想在新窗口中使用javascript包含另一个javascript文件。 I am trying to include it as follows 我想把它包括如下

<script src="/folder1/folder2/folder3/pageControl.js" type="text/javascript"></script>

Changed path folder names to protect the innocent :) 更改路径文件夹名称以保护无辜:)

The pageControl.js file is actually in the same folder as the jQuery code file and the php file, but I am trying the full path just to be safe. pageControl.js文件实际上与jQuery代码文件和php文件位于同一文件夹中,但我正在尝试完整路径只是为了安全。 I am also able to access the js file using the URL in the browser, and I can successfully include it in a static html test page using the script src tag. 我也可以使用浏览器中的URL访问js文件,我可以使用脚本src标记将其成功包含在静态html测试页面中。

After the javascript file is included in the php file, I have a call to one of its functions as follows (echo from php): 在javascript文件包含在php文件中之后,我调用了它的一个函数,如下所示(来自php的echo):

 echo '<script type="text/javascript" language="javascript">writePageControls();</script>';

So, once the php file sends all the page content back to the AJAX call, then the new window is opened, and the returned content is written to it by the jQuery code above. 因此,一旦php文件将所有页面内容发送回AJAX调用,则打开新窗口,并通过上面的jQuery代码将返回的内容写入其中。

The writePageControls line is where I get the error "Error: Object expected" when I run the page. 当我运行页面时, writePageControls行是我收到错误“Error:Object expected”的地方。 However, since the JavaScript works fine in both the static HTML page and when included "inline" in the PHP file, it is leading me to think this is a path issue of some kind. 但是,由于JavaScript在静态HTML页面中工作正常,并且在PHP文件中包含“内联”时,它使我认为这是某种路径问题。

Again, no matter what I try, my calls to the functions in the pageControls.js file do not work. 同样,无论我尝试什么,我对pageControls.js文件中的函数的调用都不起作用。 If I put the contents of the pageControl.js file in the php file between script tags and change nothing else, it works as expected. 如果我将pageControl.js文件的内容放在脚本标记之间的php文件中并且不做任何其他更改,它会按预期工作。

Based on what some of you have already said, I am wondering if the path resolution to the newly opened window is not correct. 根据你们有些人已经说过的话,我想知道新打开的窗口的路径分辨率是否不正确。 But I don't understand why because I am using the full path. 但我不明白为什么因为我正在使用完整的路径。 Also to confuse matters even more, my linked stylesheet works just fine from the PHP file. 另外,为了使问题更加混乱,我的链接样式表在PHP文件中运行得很好。

Apologies for how long this is, but if anyone has the time to look at this further, I would greatly appreciate it. 抱歉这是多长时间,但如果有人有时间进一步研究这个问题,我将非常感激。 I am stumped. 我很难过。 I am a novice when it comes to a lot of this , so if there is just a better way to do this and avoid this problem, I am all ears (or eyes I suppose...) 当涉及到很多这方面的时候我是新手 ,所以如果有更好的方法来做到这一点并避免这个问题,我全都是耳朵(或者我认为是眼睛......)

It probably isn't looking where you think it is looking to grab your javascript file. 它可能不是你认为它想要抓住你的javascript文件。

Try a server-relative format like this: 尝试像这样的服务器相对格式:

<script src="/some/path/to/pageControl.js"></script>

If that still isn't working, verify that you can type the url to your script file into your browser and get it to download. 如果仍然无效,请确认您可以将脚本文件的URL键入浏览器并下载。

Make sure that you have that within either <head> or <body> of the HTML page. 确保您在HTML页面的<head><body>具有该值。 Also, I'd double check the path to the .js file. 另外,我会仔细检查.js文件的路径。 You could do that by pasting "pageControl.js" at the root of your web address. 你可以通过在你的网址的根目录粘贴“pageControl.js”来做到这一点。

I have also had problems with a similar issue to this, and this was a real headache. 我也遇到过类似问题的问题,这真是令人头疼。 The following approach may not be elegant, but it worked for me. 以下方法可能并不优雅,但它对我有用。

  1. Make sure that your php file, just outputs what you want in your body 确保你的php文件只输出你想要的东西
  2. Add jquery to the window head dynamically 动态地将jquery添加到窗口头部
  3. Add any external script files to the window head dynamically 动态地将任何外部脚本文件添加到窗口头
  4. use jQuery html on the window's document to call html() with your loaded content on the body, so that scripts are evaluated. 在窗口的文档上使用jQuery html来调用html()以及正文中加载的内容,以便评估脚本。

For example, in your ajax success: 例如,在你的ajax成功中:

success: function(pageContent) {
        var windowFeatures = "width=800,menubar=yes,scrollbars=1,resizable=1,status=yes";
        var reportWindow = window.open("", "newReportWindow", windowFeatures);

        // boilerplate
        var boilerplate = "<html><head></head><body></body></html>";

        reportWindow.document.write(boilerplate);

        var head = reportWindow.document.getElementsByTagName("head")[0];

        var jquery = reportWindow.document.createElement("script");
        jquery.type = "text/javascript";
        jquery.src = "http://code.jquery.com/jquery-1.7.min.js";
        head.appendChild(jquery);

        var js = reportWindow.document.createElement("script");
        js.type = "text/javascript";
        js.src = "/folder1/folder2/folder3/pageControl.js";
        js.onload= function() {
            reportWindow.$("body").html(pageContent);
        };
        head.appendChild(js);


        reportWindow.document.close();

    }

Good luck! 祝好运!

Things to look for: 要寻找的东西:

  • Use Firebug (NET tab) to check if the js file is loaded with status 200 . 使用Firebug(NET选项卡)检查js文件是否加载状态200 Also check in the Console tab for any javascript errors. 还要在控制台选项卡中查看是否存在任何javascript错误。
  • Are you using HTML5 offline . 您是否使用HTML5离线 If you do, maybe it serves a cached version that doesn't include your <script> tag. 如果这样做,它可能会提供不包含<script>标记的缓存版本。
  • View the page source and make sure it includes the script tag. 查看页面源并确保它包含script标记。
  • Change the source attribute to absolute path: <script src="http://www.example.com/js/pageControl.js" type="text/javascript"></script> 将源属性更改为绝对路径: <script src="http://www.example.com/js/pageControl.js" type="text/javascript"></script>
  • Visit http://www.example.com/js/pageControl.js and make sure it shows correctly. 访问http://www.example.com/js/pageControl.js并确保其正确显示。
  • Try to place the <script> right after the <head> so that it loads first. 尝试将<script>放在<head>之后,以便首先加载。

This is all I could think of. 这是我能想到的。

You can dynamically load script by creating the element and then append it to head or other element: 您可以通过创建元素动态加载脚本,然后将其附加到head或其他元素:

reportWindow.document.write(pageContent);                      
var script = document.createElement('script');
script.src = 'pageControl.js';
script.type = 'text/javascript';
reportWindow.document.getElementsByTagName('head')[0].appendChild(script);
reportWindow.document.close();

Have you tried using the jquery $("#target_div").load(...) This also executes JS inside the output... 您是否尝试过使用jquery $("#target_div").load(...)这也在输出中执行JS ...

Read this doc to find out how to use it : 阅读此文档以了解如何使用它:

http://api.jquery.com/load/ http://api.jquery.com/load/

To me it sounds like you're expecting an unloaded script to work. 对我来说,这听起来像是在期待卸载的脚本能够正常工作。

Try taking a look here: http://ensure.codeplex.com/SourceControl/changeset/view/9070#201379 试着看看这里: http//ensure.codeplex.com/SourceControl/changeset/view/9070#201379

This is a bit of javascript that ensures that the script is loaded properly before access is attempted. 这是一些javascript,可确保在尝试访问之前正确加载脚本。 You can use this either as lazy loading (loading javascript files only when required), or, as I interpret your problem, loading a script based on the result of ajax calls. 你可以使用它作为延迟加载(仅在需要时加载javascript文件),或者,当我解释你的问题时,根据ajax调用的结果加载脚本。

What's probably happening is, you're echoing a string via an ajax callback, not inserting an element. 可能发生的是,您通过ajax回调回显字符串,而不是插入元素。 External scripts require a second GET call to load their contents, which isn't happening - only the first call happened. 外部脚本需要第二次GET调用才能加载其内容,这种情况不会发生 - 只有第一次调用才会发生。 So, when the first call includes the inline code, the DOM doesn't have to make an additional GET request to fetch the contents. 因此,当第一个调用包含内联代码时,DOM不必另外发出GET请求来获取内容。 If the DOM doesn't see the script, the DOM won't execute it, which means it's just some random tag. 如果DOM没有看到脚本,DOM将不会执行它,这意味着它只是一些随机标记。

There's a very fast way to find out. 找到一个非常快捷的方法。 In Chrome (or Firefox with the Firebug plugin installed), check the console > scripts dropdown to see all the loaded scripts. 在Chrome(或安装了Firebug插件的Firefox)中,检查控制台>脚本下拉列表以查看所有已加载的脚本。 If it's not listed, it's not loaded and the script tag you see in the markup is otherwise inert. 如果未列出,则表示未加载,并且您在标记中看到的脚本标记是惰性的。

Since it's probably just a string as far as PHP cares, you could create it as PHP DOM object and insert it properly (although this could be laborious). 因为它可能只是PHP所关心的字符串,所以您可以将其创建为PHP DOM对象并正确插入(尽管这可能很费力)。 Instead, maybe place it at the very end of the page, just before the closing body tags. 相反,也许可以将它放在页面的最末端,就在关闭正文标签之前。 (This is the preferred position for js anyway - dead last, after all the other elements on the page have loaded and are available to the DOM.) (无论如何,这是js的首选位置 - 在页面上的所有其他元素都已加载并且可供DOM使用之后,这是最后一个位置。)

HTH :) HTH :)

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

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