dsigh7478 2013-09-05 17:05
浏览 60

在ajax请求中使用带有jQuery的dataType脚本获得响应

Not sure if this should work but from a jquery ajax request with the response I want to evaluate the script being passed back. Here goes for an example.

$.ajax({
    url: some/path,
    dataType: 'script'
});

Then with my response I'm using php to spit out the javascript.

<?php
header("content-type: application/javascript");

$str = <<<EOF
    alert('help');
EOF;
echo $str;

If I'm correct I should get a alert pop-up after performing the request.

I can see from the response headers it correct:

Accept:application/json, text/javascript, */*; q=0.01 

And response is:

alert('help');

But no alert box is being triggered. Am I missing something or can this not be done this way?

Hope you can advise.

TY

  • 写回答

1条回答 默认 最新

  • dphs48626 2013-09-05 17:24
    关注

    You should call success function in $.ajax

    and execute the response

    page1.php

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js" 
    type="text/javascript"></script>
    
    <script>
    
      $.ajax({
    
          url: "page2.php",
    
          dataType: 'script',
    
          success: function(resp) {
    
              resp;  //this is your response which is contains alert('help')
    
          }
    
        });
    
    </script>
    

    page2.php

    <?php
    
    header("content-type: application/javascript");
    
    $str = <<<EOF
        alert('help');
    EOF;
    
    echo $str;
    
    ?>
    
    评论

报告相同问题?

悬赏问题

  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥15 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)