In the root of my .js file I declare:
var Doe = {
"foo": "The quick brown fox jumps over the lazy dog.",
"bar": "ABCDEFG",
"baz": [52, 97],
"testfunc": function(){alert('json function');}
}
And in my HTML:
<a id="lele" href="javascript:void(0)" onclick="Doe.testfunc()">Doe</a>
And when I click it it works, so I know it’s possible to put functions in JSON objets.
Now, in the root of the .js I declare:
$.getJSON("~/rule/2", function(data) {
alert("2: " + data.foo);
data.testfunc();
});
And the server is returning this for that url:
context.Response.ContentType = "application/json";
context.Response.Output.Write(@"{
""foo"": ""The quick brown fox jumps over the lazy dog."",
""bar"": ""ABCDEFG"",
""baz"": [52, 97],
""testfunc"": function(){alert('json function');}
}");
context.Response.Flush();
But nothing happens 🙁 Aparently because if there is an error, .getJSON will fail silently. But, if I remove the lines regarding of the function:
$.getJSON("~/rule/2", function(data) {
alert("2: " + data.foo);
});
and
context.Response.Output.Write(@"{
""foo"": ""The quick brown fox jumps over the lazy dog."",
""bar"": ""ABCDEFG"",
""baz"": [52, 97]}");
Then it works, an alert pop up with the content of the “foo” property.
What is the problem with the function? 🙁 In the moment that I put a function in the JSON object, jQuery fails.
Kind regards.
You don’t have a JSON object.
You have an object literal. Functions cannot be values of a JSON string.
JSON is only a subset of the object literal syntax. Possible values are:
(source: json.org)
Read more on json.org
This is JavaScript object:
and this is a JSON string:
See also JavaScript, JSON objects and object literal notation.
Update: In order to return and execute JavaScript, you can do the following:
You can return plain JavaScript e.g.
and use
$.ajaxwithdataType: 'script':DEMO
You can also define JavaScript objects with functions like so:
You just need to have a global function called
yourHandler(and of course still callajaxwithdataType: script).This is probably what comes closest to what you want. The difference is, that you don’t return JSON, but JavaScript, and you don’t process the object in the
successcallback, but in another function, which has to be called from within the JS you sent.See another DEMO