store return json value in input hidden field

前端 未结 6 1207
予麋鹿
予麋鹿 2020-12-04 08:57

I was wondering if it\'s possible to store the return json in a hidden input field. For example this is what my json return:

[{\"id\":\"15aea3fa\",\"firstnam         


        
6条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-04 09:41

    It looks like the return value is in an array? That's somewhat strange... and also be aware that certain browsers will allow that to be parsed from a cross-domain request (which isn't true when you have a top-level JSON object).

    Anyway, if that is an array wrapper, you'll want something like this:

    $('#my-hidden-field').val(theObject[0].id);
    

    You can later retrieve it through a simple .val() call on the same field. This honestly looks kind of strange though. The hidden field won't persist across page requests, so why don't you just keep it in your own (pseudo-namespaced) value bucket? E.g.,

    $MyNamespace = $MyNamespace || {};
    $MyNamespace.myKey = theObject;
    

    This will make it available to you from anywhere, without any hacky input field management. It's also a lot more efficient than doing DOM modification for simple value storage.

提交回复
热议问题