Problem with JSON

61 views
Skip to first unread message

Ivan Gazzola

unread,
Feb 16, 2015, 12:48:02 PM2/16/15
to web...@googlegroups.com
After last upgrade i've this problem with response.json

-----Controller  cut -------


if form.process().accepted:
     return response.json({'formkey':form.formkey,'html':XML(html_from_helpers)})


-----cut -------

The json generated by controller fails in this js because don't escape double quotes in html_from_helpers string. Is it a bug?  Before last update it worked fine ....


$('#form').submit(function(e){
e
.preventDefault();
    $
.ajax({
           type
: "POST",
           url
: "/my/url",
           data
: $('#form').serialize(), // serializes the form's elements.
           success
: function(json)
           
{
               risposta
=JSON.parse(json);; // show response from the php script.
                  $
('#form:input[name="_formkey"]').val(risposta.formkey);
                  $
('#myUL').html(risposta.html).listview('refresh');
                  $
(".risposta_flash").remove();$('<div class="ui-body ui-body-b risposta_flash" style="margin:20px;">Stato di cura inserito</div>').prependTo("#content_principale").hide().slideDown();
           
}
         
});
return false;
});    


Thx

Niphlod

unread,
Feb 16, 2015, 3:12:17 PM2/16/15
to web...@googlegroups.com
uhm. what does your shell print out of this ?


response.json({'html' : XML('<span class="foo">bar</span>')})



mine does

u'{"html": "<span class=\\"foo\\">bar</span>"}'



so it's not the issue you're describing.

Ivan Gazzola

unread,
Feb 18, 2015, 3:46:09 AM2/18/15
to web...@googlegroups.com
Ok, solved :)

The issue was in some changes in Jquery.

Now JQuery parses ajax response before than it is passed to success function, so js fails if I call "parse" on it:

risposta=JSON.parse(json);
                      ^^^^^^^^^^^^^^^

THX

Ivan

Niphlod

unread,
Feb 18, 2015, 3:45:43 PM2/18/15
to web...@googlegroups.com
to be fair, I think you encountered a minor glitch........ response.json() now sets the content-type to application/json (something that your app should have done already, but probably overlooked).
Returning a json string with text/html as content-type made jquery not aware that that string was a json, but only a string in the need to be parsed.
Moreover, JSON(something) is NOT a jquery function, it's a browser one, and not available on all browsers. That piece of code would never have worked on e.g. IE7.
Now the response is instead a json string "signalled" to be a json object, and jquery parses it correctly

<tl/dr> for the future...Don't EVER overlook content-type. Read about "dataType" on jquery's ajax().


Reply all
Reply to author
Forward
0 new messages