简体   繁体   中英

jQuery object in JSON value

Here be my first question!

I'm calling JSON via AJAX for use in a client side validation library. The library calls for me to specify where, for the current rule, I wish to insert the error message. For my static validation rules I can write an object such as:

{ 'errorlocation' : jQuery('[name="foo"]').closest('.bar') }

My validation library allows me to inject more rules after the first init, so when I submit my model by REST I could receive a server response with errors. I am currently developing that server response. I would prefer that the error response would simply be an array of validation rules so that I can later inject those rules into the same validation object that has already been created on my page. So within the response JSON I would require such a definition as that in the code snippet above.

It seems though that Backbone and jQuery's parse json algorithms can not evaluate the jQuery() value of the object even though jQuery is definitely available in the global namespace. So this doesn't work:

jQuery.parseJSON("{ 'errorlocation' : jQuery('[name=\"foo\"]').closest('.bar') }");

I have thought about just storing the "[name='foo']" and jQuerying after the parse but that doesn't work for the case where I want to chain, such as that above .closest('.bar')

Does anyone know of a JSON parser that will parse/allow variables located in the global namespace?

JSON is a data format, not a code format. Generally you want to structure your system in a way that you're passing data from the server to the client, and then your client uses the data to determine an action. So maybe you would pass the foo and .bar back as data, and another parameter to determine what function to run.

If you really HAVE to design it this way, and I advise against that, you can use eval to evaluate an arbitrary string as javascript, like this:

var errorInfo = jQuery.parseJSON(
    "{ 'errorlocation' : \"jQuery('[name=\"foo\"]').closest('.bar')\" }");

eval(errorInfo.errorocation);

Have you considered storing the whole jQuery call as a string, then running eval in the client side? Like this:

json = jQuery.parseJSON("{ 'errorlocation' : 'jQuery(\'[name=\"foo\"]\').closest('.bar')' }");
location = eval(json.errorlocation) //runs the jQuery string

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM