Question

I'm sending a message to the server via jQuery and when it gets to the Python part, +'s get added into my string :(

jQuery

// RESPONSE BUTTON:
$('.friend_response').unbind('click').bind('click', function () {

    var choice = $(this).siblings('p').text().toLowerCase(),
    theBtn     = $(this),
    id         = $('.friend_id_details').data('friend-id'),
    message    = "I would like to add you to my friend network.";

    if (choice === 'accept') {
        $(theBtn).removeClass('big_accept');
        $(theBtn).addClass('big_accept_clicked');
        $('.big_deny').attr("disabled", "disabled");
        $('.big_deny').css('cursor','auto');
        $('.button_accept p').text('Accepting...');
        sendFriendResponse(message_id, message, id, '/accept');

    } else if (choice === 'deny') {
        $(theBtn).removeClass('big_deny');
        $(theBtn).addClass('big_deny_clicked');
        $('.big_accept').attr("disabled", "disabled");
        $('.big_accept').css('cursor','auto');
        $('.button_deny p').text('Denying...');
        sendFriendResponse(message_id, ' ',     id, '/deny');
    }
});

^ Above clearly my message is just "I would like to add you to my friend network."

My postToServerWithAjax looks like:

$.ajax({
        type: postMethod,
        url: url,
        cache: false,
        // data: JSON.stringify(params),
        data: params,
        dataType: 'JSON',
        statusCode: {
            200: function (data, textStatus, jqXHR) {
                //console.log('200');
                callback(data);
            },
            201: function (data, textStatus, jqXHR) {
                //console.log('201');
                callback(data);
            },
            400: function (data, textStatus, jqXHR) {
                //console.log('400');
                callback(data);
            }
        }
    });

The params object:

Object {message: "I would like to add you to my friend network.", id: 6}

Finally in Python:

@view_config(route_name="accept:request", request_method='POST')
def accept_request(self):
    success_msg = ["You accepted the request"]
    error_msgs = ["Bacon is missing, we're looking into the issue"]

    try:
        json = self.body
        id = int(json['id'])
        message = str(json['message'])

        print id
        print message

        self.ctx.messaging.accept(id, message)
        value = {'result': 'success', 'message': random.choice(success_msg)}

    except Exception, err:
        value = {'result': 'error', 'message': random.choice(error_msgs)}
        print err

    return self.emit_json(value)

And the print statements :(

6
I+would+like+to+add+you+to+my+friend+network.

I tried just json['message'] too, but same results

Était-ce utile?

La solution

You are not sending JSON; you are sending a regular application/x-www-form-urlencoded request instead. A X-WWW-Form-URLEncoded POST body uses URL percent encoding; spaces are encoded as + characters in that encoding.

jQuery does this because data is not already a string. You must encode the data to a JSON yourself:

$.ajax({
        type: postMethod,
        url: url,
        cache: false,
        data: JSON.stringify({'params': params}),
        contentType: "application/json",
        dataType: 'JSON',
        statusCode: {
            200: function (data, textStatus, jqXHR) {
                //console.log('200');
                callback(data);
            },
            201: function (data, textStatus, jqXHR) {
                //console.log('201');
                callback(data);
            },
            400: function (data, textStatus, jqXHR) {
                //console.log('400');
                callback(data);
            }
        }
    });

Setting the correct content type for the data you send is always a good idea.

Setting the dataType argument only matters for the response, telling jQuery to decode the data received as JSON. It has no bearing on how data is sent to the server.

It looks as if you are using Pyramid for the Python side; you want to use Request.json_body to access the JSON-encoded data as a Python object.

Autres conseils

Not sure what is going on, but having the same problem again...

First try in Python

for char in title:
    if char in "+":
        cleaned_title = title.replace(char, ' ')

2nd attempt, better in jQuery & Python

titleVar = $('#the-title').val();

if (titleVar.indexOf(' ')) {
    var titleCleaned = titleVar.split(' ').join('%20');
}

Then in Python:

import urllib2
if 'params' in self.body:
    params = self.body['params']
    pars = urllib2.unquote(params)
    cleaned = json.loads(pars)

^ Much better then doing a for loop... or trying to fix this crap below:

Just cannot figure out what is the exact perfect setup for a jQuery Ajax call:

var invokeServerWithJSON = function(url, params, callback, postMethod) {

    WHOAT.analytics.trackPageView(url);
    $.ajax({
        type: postMethod,
        url: url,
        cache: false,
        data: {'params': JSON.stringify(params)},
        // contentType: "application/json",
        // success: callback,
        // dataType: 'JSON',
        statusCode: {
            200: function (data, textStatus, jqXHR) {
                callback(data);
            },
            201: function (data, textStatus, jqXHR) {
                callback(data);
            },
            400: function (data, textStatus, jqXHR) {
                callback(data);
            }
        }
    });
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top