ajax执行脚本

时间:2012-02-23 23:03:12

标签: javascript jquery ajax

好吧,我觉得我已经接近但事情仍然无效:

我有以下功能

function showRecaptcha()
  {
  alert("test2");
   $.getScript("/plaoul/commentfiles/recaptchaJS.php", function(data, textStatus, jqxhr) {

     console.log(data); //data returned
     console.log(textStatus); //success
     console.log(jqxhr.status); //200
     console.log('Load was performed.');
  });
}

该函数应该调用以下javascript:http://www.jeffreycwitt.com/plaoul/commentfiles/recaptchaJS.php(随意查看此页面 - 它在这里工作得很好,但是当我通过ajax调用它时不行)

这是一个javascript,执行时会显示recapatcha表单。

到目前为止,控制台日志返回以下内容:

<script type="text/javascript" src="http://www.google.com/recaptcha/api/challenge?k=6LfDj8gSAAAAAG53PTtr-1665awLtERThvylvnUY"></script>
<noscript>
    <iframe src="http://www.google.com/recaptcha/api/noscript?k=6LfDj8gSAAAAAG53PTtr-1665awLtERThvylvnUY" height="300" width="500" frameborder="0"></iframe><br/>
    <textarea name="recaptcha_challenge_field" rows="3" cols="40"></textarea>
    <input type="hidden" name="recaptcha_response_field" value="manual_challenge"/>
</noscript>
 comment_navbar_jsfunctions.js:129success
 comment_navbar_jsfunctions.js:130200
 comment_navbar_jsfunctions.js:131Load was performed.

但我希望<script>实际显示为我的页面div#commentWindow上的div中的recpatcha图像。一旦我使用getScript编写脚本,我就无法弄清楚如何让脚本显示在div#commentWindow中。你能救我吗?

2 个答案:

答案 0 :(得分:1)

由于您通过AJAX获取此HTML,因此您不必担心<noscript>。所以你可以这样做:

//get plain-text from local PHP file
$.get('/plaoul/commentfiles/recaptchaJS.php', function (response) {

    //get the source of the `<script>` element in the server response
    var source = $(response).filter('script')[0].src,
        script = document.createElement('script');

    //set the type of our new `<script>` element and set it to `async = true`
    script.type  = 'text/javascript';
    script.async = true;

    //set the source of the new `<script>` element to the one in the server response
    script.src = source;


    //add the new `<script>` element to the DOM
    var s = document.getElementsByTagName('script')[0];
    s.parentNode.insertBefore(script, s);
});

您可能会注意到此代码中的一部分来自Google Analytic异步跟踪代码(创建新<script>元素的部分)。

答案 1 :(得分:0)

所以你只想获取该PHP文件的输出并将其呈现给页面?

您是否尝试过$('#commentWindow').load('/plaoul/commentfiles/recaptchaJS.php');

编辑 - 抱歉,应该是.loadhttp://api.jquery.com/load/