3

如果这是一个愚蠢的问题,我真的很抱歉,但我似乎无法让它发挥作用。正如标题所说,我正在尝试加载一个外部 js 文件并将其作为纯文本分配给一个变量。该项目是一个简单的 js“编译器”,它将多个 js 文件拼接在一起并将它们缩小为一个。我目前正在使用 $.get() 方法并将响应附加到字符串。

问题是处理上述问题的js文件也需要包含在最终的缩小文件中。我可以加载所有其他文件并将它们拼接在一起,但是当我将这个主文件加载到自身中以获取 js 文件时,它似乎会评估并覆盖自身,因此会停止该过程。

目前我已经通过将副本加载为 .txt 文件来解决问题,但这意味着我必须保持两个文件是最新的,这并不理想。

我找到了这篇文章,但它指的是通过头部的脚本标签加载的 javascript。

任何帮助,将不胜感激。我很乐意发布代码,但不确定哪些位会有用。

更新:我可能应该提到该项目需要完全在客户端运行,所以我不能使用 PHP/.NET 页面。我加载的所有文件都在同一个域中。

4

2 回答 2

0

Note that $.get() and $.post() and $.ajax() are all the same thing.

$.get and $.post are just shorthand versions of $.ajax() that come with presets (obviously, type: "GET" and type:"POST" for one...). I prefer using $.ajax because the format can be more structured, and therefore easier to learn/use.

Javascript/jQuery would look something like this:

<script type="text/javascript">

    $(document).ready(function() {
        $.ajax({
            type: "POST",
            url: "loadmyfile.php",
            data: 'filename=js/myscript.js',
            success: function(whatigot) {
                //alert('Server-side response: ' + whatigot);
                $('#myhiddentext').val(whatigot);
            } //END success fn
        }); //END $.ajax
    }); //END $(document).ready()

</script>

Important: Note that you would need to do all the post-AJAX processing inside the success function. See this link for some simple AJAX examples.

Note that you can send data across to the PHP file by specifying a data: parameter in the AJAX code block. Optionally, you can leave out that line and simply hard-code the filename into the PHP file.

The text of the retrieved js file comes back into the AJAX success function (from the PHP file) as a string in the variable specified as the function param (in this case, called 'whatigot'). Do what you want with it; I have stored it inside a hidden <input> control in case you wish to retrieve the text OUTSIDE the AJAX success function.

PHP would look something like this:

loadmyfile.php

<?php
    $fn = $_POST['filename'];

    $thefile = file_get_contents($fn);
    echo $thefile;

References: PHP file_get_contents

于 2013-08-23T16:28:47.487 回答
0

尝试使用Ajax.get()

var script;
$.get('script.js', function(data) {
  script = data;
});

对于 Ajax.get() 它将在您的域内工作,您不能调用外部域,如果您的应用程序需要加载外部 JS 文件,那么我的猜测是您必须使用 PHP 或其他服务器端语言:

var script;
$.get('getScript.php', {url: "http://test.com/script.js"}function(data) {
  script = data;
});

getScript.php中,您可以使用CURLfile_get_contents

于 2013-08-23T16:31:17.503 回答