从AJAX Success解析字符串以作为JQuery运行

在我的HTML页面上,我有一个AJAXpost来获取一些数据。 返回的数据包含一个字符串,该字符串的内容是原始javascript。

$.ajax({ url: '@Url.Action("GetPropertyDataForInstance", "Local_Data")', type: 'POST', dataType: 'json', data: instancePropertyRequest, contentType: 'application/json; charset=utf-8', success: function (response) { var javscriptRawString = response.javascriptToExecute; var alertString = response.data; } }) 

javscriptRawString的内容:

 alert(alertString); 

在我得到这个javascriptRawString后,我该怎么办才能直接执行javascript里面的??

这比eval略好,因为eval是邪恶的;)

 (new Function(response.data))() 

使用eval是邪恶的,因为可能存在许多安全漏洞。 您正在全局范围内执行代码。 通过在自己的范围内执行, Function可以采用不同的方式。

new Function也更快

在你的情况下

 $.ajax({ url: '@Url.Action("GetPropertyDataForInstance", "Local_Data")', type: 'POST', dataType: 'json', data: instancePropertyRequest, contentType: 'application/json; charset=utf-8', success: function (response) { (new Function(response.data))() } }) 

new Function从原始文本创建一个新函数。

()()立即执行该函数

如果你用ajax获得你的function,我还会添加一些额外的检查和标题。 检查一下。

https://stackoverflow.com/a/17468822/2450730

编辑

如果你想从ajax传递params

 //raw ajax response var x='param'; alert(x) 

如果你想从ajax中传递params(不好)。

 success: function (response) { var x='param'; (new Function(response.data))(x) } 

生的

 alert(x); 

编辑2

如果你得到一个对象1.the script 2.the params

那么你需要定义一个参数名称。在这种情况下’x’。

JS

  (new Function('x',response.script))(response.param) 

RAW response.script

  alert(x) 

更多论点:

 (new Function('a','b','c','alert(a+b+c)'))(1,2,3) // 123 

测试它http://jsfiddle.net/pLQzd/ 阅读它https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function滚动到底部。

但是当您从同一个ajax调用中获取包含该函数和vars的对象时

我只想创造一些已经描述过的东西。

生的

 var param='hello'; alert(param); 

甚至更简单

 alert('hello'); 

您可以通过eval运行任何字符串:

 eval('alert("hello world")'); 

确保你确切地知道你正在评估什么。

为什么不用整数格式化ajax响应?

例如

 $.ajax({ //Your AJAX }).done(function(response) { //Let's say response from the script is 1. switch(response) { case 1: alert('Hello world'); break; //case ... etc. } }); 

永远不要使用eval(); 除非你绝对别无选择。

eval ===邪恶!