从 ajax 请求上使用 dataType 脚本和 jQuery 获取响应

Getting response from Using dataType script with jQuery on ajax request

本文关键字:脚本 jQuery 获取 响应 dataType ajax 请求      更新时间:2023-09-26

不确定这是否应该有效,但从带有响应的 jquery ajax 请求中,我想评估被传回的脚本。这里举个例子。

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

然后通过我的回应,我正在使用php来吐出javascript。

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

如果我是对的,我应该在执行请求后收到警报弹出窗口。

我可以从响应标头中看到它是正确的:

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

回应是:

alert('help');

但是没有触发警报框。我错过了什么还是不能这样做?

希望你能提供建议。

你应该在 $.ajax 中调用成功函数

并执行响应

页1.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>

页2.php

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