如何通过Ajax响应返回的脚本标签中执行的JavaScript

人气:1,034 发布:2022-09-11 标签: jquery javascript ajax

问题描述

我要送一个jQuery GET请求,像这样:

I'm sending a jquery get request like so:

$.get($(this).attr("href"), $(this).serialize(), null, "script");

我希望收到的答复将包裹在脚本标记。

The response I expect to receive will be wrapped in script tags.

我理解的浏览器不执行响应,除非它不返回脚本标记。通常我会删除标记的反应,但在这种情况下,我没有进入code运行在远程机器上,这样不能带出标签的来源。

I understand the browser doesn't execute the response unless its returned without the script tags. Normally I would remove the tags from the response but in this situation I don't have access to the code running on the remote machine so cannot strip out the tags at the source.

有没有一种方法可以让我带出从响应客户端的脚本标记和执行JavaScript?

Is there a way I can strip out the script tags from the response client side and execute the javascript?

推荐答案

您应该能够做到以下几点:

You should be able to do the following:

$.get($(this).attr("href"), $(this).serialize(), function(data){
   script = $(data).text();
   eval(script);
});

232