JQuery ajax coding data

I have this code (below).

$.ajax ({ type: "POST", url: "../WebServices/Feedback.svc/sendfeedback", dataType: 'json', async: false, data: '{"stars": "' + stars + '", "rating" : "' + rating + '", "note" : "' + encodeURIComponent(note) + '", "code" : "' + code + '", "permission" : "' + permission + '"}', contentType: "application/json; charset=utf-8" }); 

I use this to transfer data to a web service, but the problem is if there are any characters (, / ?: @ and = + $ #). I put in an encodeURIComponent that works fine, and then in the web service I put them back.

What I ask is, is there a better way to do this? It seems a little crazy that I have to encode a string every time before passing it.

thanks

+5
jquery ajax uri character-encoding
source share
2 answers

Is the web service yours or are you using another web service? Why didn't the web service accept (, / ?: @ AND = + $ #)?

jQuery $. ajax default contentType is application / x-www-form-urlencoded , which means jQuery will encode the content. However, since you specified a different type of contentType, the data is not encoded, so you need to make your own encoding.

Alternatively, you can try to remove the contentType parameter and pass your content in the usual way (without encodeURICompnent ).

 $.ajax ({ type: "POST", url: "../WebServices/Feedback.svc/sendfeedback", dataType: 'json', async: false, data: '{"stars": "' + stars + '", "rating" : "' + rating + '", "note" : "' + note + '", "code" : "' + code + '", "permission" : "' + permission + '"}', }); 
+4
source share

pass data through an object instead of a string:

 $.ajax ({ ... data: {stars: stars, rating: rating...(etc)} }); 
+10
source share

All Articles