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>";
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.
We can pass an object to a JavaScript function, but the arguments must have the same names as the Object property names.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With