sending unicoded strings in ajax.post request
-
22-06-2021 - |
Domanda
I am using "livechatstarterkit" for chatting functionality in my mvc web app. But my web application is in a right to left language and users have names in Persian.
The problem here is that when a user with Persian name log-in as operator his name encoded cause of the following script:
<script type="text/javascript">
var intervalId;
var chatId = '@(Model)';
var lastMsgId = 0;
var opname = '@ViewBag.opname';
$(document).ready(function () {
getMsgs();
intervalId = window.setInterval(function () {
getMsgs();
}, 3210);
$('#chatText').keyup(function (e) {
if (e.keyCode == 13) {
$.post('/chat/addmsg', { id: chatId, from: opname, msg: $('#chatText').val() }, function (data) { getMsgs(); });
$('#chatText').val('');
}
});
.....
But as I debug my app, I see the messages from operator are not beign sent, in fact the $.post('/chat/addmsg'....
code is not executed and request is not sent to proper action.
here is some exaple of opname in jscript : "پشتیبانی
"
Soluzione
Replace:
var opname = '@ViewBag.opname';
with:
var opname = @Html.Raw(Json.Encode(ViewBag.opname));
Also to test if Enter was pressed in a cross browser fashion, your code should look like this:
$('#chatText').keyup(function (e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 13) {
var url = '@Url.Action("addmsg", "chat")';
var msg = $(this).val();
$.post(url, { id: chatId, from: opname, msg: msg }, function (data) {
getMsgs();
});
$(this).val('');
}
});
Altri suggerimenti
$.ajax({
url:"ax.php?action=post&save=1",
type: "POST",
data:
{ tabName: "basic",
rid: $("textarea#id").val(),
col:"id",
val:$(this).prev().val() },
success:function (result){ setSpan(result);},
dataType:"html", contentType: "text/plain; charset=UTF-8" } )
What about using $.ajax
function so that you can set contentType
property.
When sending data to the server, use this content-type. Default is "application/x-www-form-urlencoded", which is fine for most cases. If you explicitly pass in a content-type to $.ajax() then it'll always be sent to the server (even if no data is sent). Data will always be transmitted to the server using UTF-8 charset; you must decode this appropriately on the server side.