简体   繁体   中英

Is this jQuery AJAX post saving data incorrectly?

    $.ajax({
        type: 'POST',
        url: '/users',
        data: {
            _method : 'PUT',
            user : {
                guides : {
                    step1 : true,
                    step2 : true
                }
            }
        }
    });

Is this saving correctly? I want this json data in a rails serialized field but It's saving incorrectly as follows below which is causing errors.

User.guided:

--- "{\"step1\"=>\"true\", \"step2\"=>\"true\"}"

Then when I do the following in the rails view:

guides = [<%= current_user.guides.try(:html_safe)%>];

It outputs with => instead of the expected : .

First of all you could try to use JSON.stringify() otherwise jQuery will use $.param() to serialize your data. But your main issue is that you want a JSON string, and not the YAML that is generated. As far as I now something like

guides = [<%= current_user.guides.to_json %>];

should do the trick. Also, maybe I'm not 100% sure but you probably don't need to use html_safe on this, because it's already escaped, although can't tell how it will be rendered in view

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