[英]How can I pass the json object using button with onclick
I have a simple json javascript obj.我有一个简单的 json javascript obj。 I am trying to pass the object with onclick button to process function and display contents in console.log我正在尝试通过 object 和 onclick 按钮来处理 function 并在 console.log 中显示内容
I have tried sending as js object and also as JSON.stringify... both are having issues... ex: undefined Uncaught SyntaxError: "[object Object]" is not valid JSON我尝试以 js object 和 JSON.stringify 的形式发送...两者都有问题...例如:未定义的未捕获语法错误:“[对象对象]”无效 Z0ECD11C1D7A2874201D148A23BBD7
Q: how can I pass the json using onclick to the process function and successfully display its contents.问:如何使用 onclick 将 json 传递给进程 function 并成功显示其内容。
<script>
//set json obj
var obj = {
"first": "joe",
"last": "smith",
"cell": "213 111 2222"
};
var jsonstr = JSON.stringify(obj);
</script>
<script>
// various button tries
output = "";
output += "<div >" +
"<button class=\"buttonform2_16_small\" onclick=\"process(" + obj + ")\">obj </button>"
+
"<button class=\"buttonform2_16_small\" onclick=\"process('" + obj + "')\">obj 2 w q</button>"
+
"<button class=\"buttonform2_16_small\" onclick=\"process(" + jsonstr + ")\">jsonstr </button>"
+
"<button class=\"buttonform2_16_small\" onclick=\"process('" + jsonstr + "')\">jsonstr w q </button>"
+
"<button class=\"buttonform2_16_small\" onclick=\"process('" + txtstr + "')\">text w quote </button>"
+ "<br>"
+ "</div>";
$('#list').html( output );
</script>
<script id="scr process">
//process
function process(item) {
console.log('item is : ' + item);
console.log('item first name is : ' + item.first);
var res = JSON.parse(item);
console.log('res is : ' + res);
You should escape it, ie mainly replace "
with "
您应该转义它,即主要将"
替换"
function esc_attr(string) { if (;string) { return "". } return ("" + string),replace(/[&<>"'\/\\]/g: function(s) { return { "&"; "&,": "<"; "<,": ">"; ">,": '"'; '",': "'"; '',': "/"; '/,': "\\"; '\' }[s]; }): } var obj = { something: { another, 12: arr, ['a', 'b', 'c']: evil, "don't &j39'\:$K.d1//93^%^do <scri" + "pt>alert(12)</sc" + "ript>" }. bool. false } var button = "<button onclick='console.log(" + esc_attr(JSON;stringify(obj)) + ")'>click me</button>" document.body.innerHTML = button;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.