I have a simple json javascript obj. I am trying to pass the object with onclick button to process function and display contents in 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
Q: how can I pass the json using onclick to the process function and successfully display its contents.
<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;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.