本文介绍了Java在不使用引号的情况下向json对象添加函数.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用Java构建一个json对象.我需要将一个函数传递到我的javascript中,并使用jquery $ .isFunction()对其进行验证.我遇到的问题是我必须将json对象中的函数设置为字符串,但是json对象正在将周围的引号与对象一起传递,导致函数无效.在没有引号出现在脚本中的情况下如何执行此操作.

I'm building a json object in java. I need to pass a function into my javascript and have it validated with jquery $.isFunction(). The problem I'm encountering is I have to set the function in the json object as a string, but the json object is passing the surrounding quotes along with object resulting in an invalid function. How do I do this without having the quotes appear in the script.

示例Java

JSONObject json = new JSONObject();
json.put("onAdd", "function () {alert(\"Deleted\");}");

jQuery脚本

//onAdd output is "function () {alert(\"Deleted\");}"
//needs to be //Output is function () {alert(\"Deleted\");}
//in order for it to be a valid function.
if($.isFunction(onAdd)) {
    callback.call(hidden_input,item);
}

有什么想法吗?

推荐答案

正在运行

onAdd = eval(onAdd);

应该将您的字符串转换为函数,但是在某些浏览器中却存在问题.

should turn your string into a function, but it's buggy in some browsers.

IE中的解决方法是使用

The workaround in IE is to use

onAdd = eval("[" + onAdd + "]")[0];

请参见 a eval()和new Function( )是同一件事吗?

这篇关于Java在不使用引号的情况下向json对象添加函数.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-05 09:04