[英]How to extract Javascript code block from ajax reponse with jquery?
如何使用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>';
您可以通過簡單的字符串拆分來做到這一點:
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')
當您的響應中包含多個腳本時,就會出現問題。 但是你可以類似地處理
您可以嘗試這樣的事情:
<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>
我分解了代碼,以便可以解釋每個步驟。 可能更簡潔。 請注意,這僅適用於單個腳本塊。 如果有很多,您需要做一些循環,而不僅僅是調用$ script.text()。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.