0

jqueryでajax応答からJavascriptコードブロックを抽出するには? 他のタグ (この場合は div タグ) の横に、javascript コードを実行または評価しない、

get_js.html で

<script> 
    $(function(){
       $.get('src.php',function(Source) {
         // In Here I want to get Javscript Code Block from string(Source)
         // Only javascript code block, not other tags
         var Code = GET_SCRIPT(Source);
         $('#code_block').val(Code);
    });
</script>
<textarea id="code_block">
</textarea>

src.phpで

echo '<script>alert("this is script code, which is not to be excuted")</script><div>Blah..Blah..</div>';
4

2 に答える 2

1

これは、単純な文字列分割によって行うことができます。

var str = "<script>alert('this is script code, which is not to be excuted')</script><div>Blah";
var script = str.substring(str.indexOf('<script>')+8, str.lastIndexOf("</script>"));
console.log(script);

上記のコードは次のとおりです。

alert('this is script code, which is not to be excuted')

応答に複数のスクリプトがある場合に問題が発生します。しかし、あなたはそれを同様に扱うことができます

于 2013-07-16T05:30:30.870 に答える
0

You could try something like this:

<textarea id="code_block"></textarea>
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script>
    $.ajax('src.php').success(function(resp) {
        var $container = $('<div />'), // container element for freeform response block
            $script, script;
        $container.append(resp); // add the response content to the container so you can search it

        $script = $container.find('script'); // Locate the script block
        script = $script.html(); // Get the text only

        $('#code_block').val(script);
    });
</script>

I broke down the code so I could explain each step; it could be more concise. Note that this would only work for a single script block. If there were many you'd need to do some looping instead of just calling $script.text().

于 2013-07-16T05:55:27.410 に答える