Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a JSON object in javascript function as a function parameter?

In my js function,I create a div and a link ,when click the link,I will pass a parameter the another js funcion?What's wrong with my code?

js function1

 //pass a json:the browser show wrong:SyntaxError: missing ] after element list
 //passJson([object Object])
 var dataItem=getDataItem();//a json object which has title and name property
 var divStr="<div><a style='cursor: pointer' onclick='passJson(" + dataItem +")'><span title='spantitle'><i class='icon-mouse'></i></span></a>;</div>";

So I try to add the "[]" to the function,but it still show wrong.

js function2

 //pass a json:the browser show wrong:SyntaxError: missing ] after element list
 //passJson([object Object])
 var dataItem=getDataItem();// a json object which has title and name property
 var divStr="<div><a style='cursor: pointer' onclick='passJson([" + dataItem +"])'><span title='spantitle' ><i class='icon-mouse'></i></span></a>;</div>";
like image 432
flower Avatar asked Apr 13 '14 09:04

flower


People also ask

How do you pass a JSON object as a parameter in Java?

Either use an export mapping to create a JSON string that you can pass to the Java action and then create a JSON object again from that string or just pass a root object to the Java and then in Java retrieve all the attached objects over the references to that root object.

Can I pass object as parameter JavaScript?

We can pass an object to a JavaScript function, but the arguments must have the same names as the Object property names.

How do I pass a JSON object?

Send JSON Data from the Client SideUse JSON. stringify() to convert the JavaScript object into a JSON string. Send the URL-encoded JSON string to the server as part of the HTTP Request. This can be done using the HEAD, GET, or POST method by assigning the JSON string to a variable.


1 Answers

Typically, you don't call it a JSON object. You just call it a JavaScript object.

The way your code is, you don't need to do string concatenation. You can just do onclick='passJson(dataItem)' as in

http://jsfiddle.net/6LzCA/5/

function passJson(obj) {
    console.log(obj);
}

var dataItem={ title: "hello", name: "snoopy" }; //a json object which has title and name property

var divStr="<div id='foo'><a style='cursor: pointer' onclick='passJson(dataItem)'><span title='spantitle'><i class='icon-mouse'></i>hmmm</span></a>;</div>";

$("body").append(divStr);

and it will work when you click on the link "hmmm".

You probably want to add the markup separately, and then bind a click handler to the link, because typically, we would like to go with the approach of unobtrusive JavaScript.

like image 122
nonopolarity Avatar answered Oct 19 '22 23:10

nonopolarity