java code
pResponse.setHeader("content-type", "text/plain;chartset=UTF-8");
pResponse.setContentLength(resultsJson.length());
Writer out = pResponse.getWriter();
String escapedJsonString = StringEscapeUtils.escapeJavaScript(resultsJson);
out.write(escapedJsonString);
The purpose to escape the return text is because there are some accented character in 'resultsJson' and even though I set charset=UTF-8, I still get garbled text from ajax. check this question from me ajax garbled text
ajax code
var option = {
type : 'POST',
url : $('#csrOrderExportform').attr('action'),
data : $('#csrOrderExportform').serialize(),
beforeSend : preAjaxReqest,
dataType:'text',
error : function(data, statustext, error){
$(".searchSubmitBtn").removeAttr("disabled");
setErrorMessage('No Records Found!');
},
success : function(data){
if (data) {
alert(unescape(data));}
}
};
$.ajax(option);
response text
[{\"orderNumber\":\"S301020000\",\"customerFirstName\":\"\u5F20\u79D1\",\"customerLastName\":\"\u5F20\u79D1\",\"orderStatus\":\"PENDING_FULFILLMENT_REQUEST\",\"orderSubmittedDate\":\"May 13, 2015 1:41:28 PM\"}]
after unescape the text from jquery, I am getting the same text.
expected output
[{"orderNumber":"S301020000","customerFirstName":"张科","customerLastName":"张科","orderStatus":"PENDING_FULFILLMENT_REQUEST","orderSubmittedDate":"May 13, 2015 1:41:28 PM"}]
This should work:-
pResponse.setContentType("application/json");
pResponse.setContentLength(resultsJson.length());
Writer out = pResponse.getWriter();
String escapedJsonString = StringEscapeUtils.escapeJavaScript(resultsJson);
out.println(escapedJsonString);
Related
Hi I am trying to send a JSON array from a POST to Spring backend.
In my Javascript:
$('#tblfilelisting tbody tr').each(function () {
var namerecord = {
No: $(this).find('.assignindex').text().trim(),
Name: $(this).find('.getname').val(),
File: $(this).find('.getfilename').text().trim(),
Status: $(this).find('.radioname:checked').val()
};
nameList.push(namerecord);
});
var jasonData = new FormData();
jasonData.append('arrStr', JSON.stringify(nameList));
$.ajax({
type: 'POST',
url: '/api/CheckValidateBeforeSave',
data: jasonData,
contentType: 'application/json',
processData: false,
beforeSend: function () {
//
},
success: function (data) {
if (data.code != '200') {
return false;
}
var get = data.jasonResult;
for (var i = 0; i < get.length; i++) {
appendResultResponse(get.No[i], get.Name[i], get.File[i], get.Status[i], get.Result[i]);
appendErrorMess(get.No[i], get.hasDuplicated[i]);
}
$('#uploadFileConfirmation').modal('show');
},
error: function (err) {
//
},
});
In my REST Controller, I have:
#PostMapping(value = "/CheckValidateBeforeSave", produces = "application/json", consumes = "application/json")
#ResponseBody
public FileManagement CheckValidateBeforeSave(#RequestBody FileManagement fileManagement) {
fileManagementService.checkMultipleFiles(fileManagement);
return fileManagement;
}
But the error that I got was :
JSON parse error: Unexpected character ('-' (code 45)) in numeric value: expected digit (0-9) to follow minus sign, for valid numeric value; nested exception is com.fasterxml.jackson.core.JsonParseException: Unexpected character ('-' (code 45)) in numeric value: expected digit (0-9) to follow minus sign, for valid numeric value
But my POST request does not have - sign:
------WebKitFormBoundaryId7kxO7B9rozEwHv
Content-Disposition: form-data; name="arrStr"
[{"No":"1","Name":"dd","File":"Test PDF 2.pdf","Status":"on"}]
------WebKitFormBoundaryId7kxO7B9rozEwHv--
line-awesome.woff2?v=1.1. CheckValidateBeforeSave common.js util.js AuthenticationService.Authenticate?1shttp%3A%2F%2F…zaSyBTGnKT7dt597vo9QgeQ7BFhvSRP4eiMSM&token=29026
Please help. Thanks.
The reason you are getting JSON parse error is that you are not actually sending a data of JSON format. Instead, your data have FormData format.
There are two ways you can fix it.
1. You only need to send the nameList
data: JSON.stringify(nameList)
2. You want to send it as FormData (optionally along with other data)
data: {formdata: jasonData, var2: "other data"}
I am doing an ajax call to the java servlet. The servlet responds with a JSON Array with a charset set to UTF-8. However, once I get a response in the AJAX call, I get ??? characters in my strings. I went through a lot of testing and research and could not find a possible solution.
AJAX CALL:
$.ajax({
type: 'POST',
data: {curTableName: curTableName,curTableID: curTableID},
dataType: 'json',
url: '../ShowProducts',
success: function(productInfo){
var noOfProducts = productInfo.length;
for(var i = 0; i < noOfProducts; i++)
{
product.push(productInfo[i].product.substr(0,25) + "...");
webshop.push(productInfo[i].webshop);
price.push(productInfo[i].price);
availability.push(productInfo[i].availability);
lastChecked.push(productInfo[i].lastChecked);
checkFreq.push(productInfo[i].checkFreq);
url.push(productInfo[i].url);
DisplayProductInfo(product[i],webshop[i],price[i],availability[i],lastChecked[i],checkFreq[i],url[i]);
}
}
});
And my Java Servlet Response:
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(jsonArr.toString());
Based on my own research the java servlet seems to be correct, and maybe there is an issue with the javascript. Anybody has any good ideas. All help is greatly appreciated. :)
I have managed to get it work. The problem resided in the fact that the JSON needed to be encoded in the servlet, and decoded in the javascript. Thank you - isah.
CODE CHANGES:
AJAX CALL:
$.ajax({
type: 'POST',
data: {curTableName: curTableName,curTableID: curTableID},
dataType: 'json',
url: '../ShowProducts',
success: function(productInfo){
var noOfProducts = productInfo.length;
for(var i = 0; i < noOfProducts; i++)
{
productInfo[i].product = decodeURIComponent(productInfo[i].product);
productInfo[i].product = productInfo[i].product.replace(/\+/g, ' ');
product.push(productInfo[i].product.substr(0,25) + "...");
webshop.push(productInfo[i].webshop);
price.push(productInfo[i].price);
availability.push(productInfo[i].availability);
lastChecked.push(productInfo[i].lastChecked);
checkFreq.push(productInfo[i].checkFreq);
url.push(productInfo[i].url);
DisplayProductInfo(product[i],webshop[i],price[i],availability[i],lastChecked[i],checkFreq[i],url[i]);
}
}
});
JAVA SERVLET:
productSplit[0] = URLEncoder.encode( productSplit[0], "UTF-8");
Additional line has been added to Java servlet. Now the title gets encoded, and only after that it goes to the JSON object.
I am sending the the value from my jsp to my servlet in url parsing.
The value contains the special character (), but when I am receiving the value it is ( and ).
How to decode this back to ()?
jsp code
var devicename=document.getElementById('s_loc_1').value;
var param=devicename;
param=encodeURIComponent(devicename);
var updatedevsaturl="http://"+window.location.host+"/services/PCEquipmentDevice?productid={}&action=updatePCDeviceStatus&reqby={}¶m="+param;
var productId=document.getElementById('pid').value;
updatedevsaturl=sustituteParameter(updatedevsaturl,productId);
updatedevsaturl=sustituteParameter(updatedevsaturl,userUpi);
alert(updatedevsaturl);
$.ajax({
type : "GET",
timeout:20000,
url : updatedevsaturl,
async: false,
dataType : "xml",
success: function(data) { }, error: function (xhr, ajaxOptions, thrownError) {
alert('Service Unavailable - VPU List');
}
});
java code to decode
if(action.equals("updatePCDeviceStatus")){
System.out.println("param: "+param);
//String decodeparam3 = new String(param.getBytes("UTF-8"),"ASCII");
//String decodeparam3 =URLDecoder.decode(param, "UTF-8");
String decodeparam3= URLDecoder.decode(param, "ISO-8859-1");
System.out.println("decodeparam132 "+ decodeparam3);
I tried all the ways give on net but didnt workenter code here
input at jsp 2-in-1 Laptop (12.5 inches)
output at servlet 2-in-1 Laptop ྫྷ.5 inches)
This is ASCII code for "(". Look at this answer Java: How to unescape HTML character entities in Java? . You have to create a char from that html entity.
On Ajax success call, I'm getting already parsed data in JSON format from a Controller.
I want to read that data, so while I'm doing below one, I am getting undefined as an error.
How can I solve this?
success : function(response) {
alert(response.operatorId);
},
Here is an example of working code
success: function(json) {
console.log(JSON.stringify(json.topics));
$.each(json.topics, function(idx, topic){
$("#nav").html('' + topic.link_text + "");
});
}
It appears that the response coming into success function is not a JSON object. COuld you check if you have following set in your ajax call.
dataType: 'json',
contentType : 'application/json'
Alternatively, you may use the following to parse the json string to json object and then use dot notation to access the properties
success : function(response) {
var jsonData = $.parseJSON(response)
alert(jsonData.operatorId);
},
I have a Datatable created, and I'm using jeditable plugin to edit cells to push back data. I can edit the cells but when I hit enter and it sends back to my URL Rest endpoint (which I just have a System.out.println to see the data) I get this error from firebug
"NetworkError: 415 Unsupported Media Type - my rest endpoint url"
My endpoint is expecting an Object in JSON, jeditable is only sending some string parameters. So I need to wrap it up.
Let me post my datatable initialization along with jeditable init.
var computerTable = $("#table_computerTable ").dataTable({
"bProcessing": true,
"bServerSide": true,
"bInfo":false,
"bAutoWidth":false,
"bScrollInfinite":true,
"sAjaxSource": ApiUrl(),
"aoColumns":[ // Maps <th> elements in html to JSON data
{"mData": "id"},
{"mData": "description","sClass" : "read_only"},
{"mData": "serial"},
{"mData": "daily"}
],
"aoColumnDefs":[
{"sName":"id","bVisible":false, "aTargets": [0]},
{"sWidth": "55%","aTargets": [1]},
{"sName":"serial","bVisible":false, "aTargets": [2]},
{"sName":"daily","aTargets":[3]}
],
"fnServerData": function ( sSource, aoData, fnCallback ) {
$.getJSON( sSource, aoData, function (json) {
map = {};
map["aaData"] = json;
fnCallback(map);
});
},
"fnRowCallback": function(nRow, aData, iDisplayIndex ){
$(nRow).attr("id",aData["id"]); // Change row ID attribute to match database row id
return nRow;
}
}).makeEditable({
sUpdateURL: getApiUrl() + "cpu/save",
sReadOnlyCellClass: "read_only",
ajaxoptions:{
dataType: "json",
type: 'POST'
}
});
This is the data I get back when I send the POST (read from firebug)
columnId 3
columnName daily
columnPosition 2
id 24
rowId 0
value 50
What I would like to do is initialize an object and send back all the data I want in that. The ID / Serial / Hourly(the new value)
I don't know enough jquery, javascript to know where to begin with that modification.
Any suggestions?
Edit your makeEditable like this:
makeEditable(
{
sUpdateURL: function(value, settings)
{
var sentObject = {}
var rowId = oTable.fnGetPosition(this)[0];
var columnPosition = oTable.fnGetPosition(this)[1];
var columnId = oTable.fnGetPosition(this)[2];
var sColumnTitle = oTable.fnSettings().aoColumns[columnId].sTitle;
sentObject["rowid"]= rowId
sentObject["columnpos"]= columnPosition
sentObject["columnId"]= columnId
sentObject["sColumnName"]= sColumnTitle
sentObject["valueOfCell"]=value
sentObject["Serial"]="serialnumber"
sentObject["Hourly"]="somevalue"
$.ajax({
type: "POST",
url: "url",
data: "sentObj="+JSON.stringify(sentObject)
})
return value;
},
sSuccessResponse: "IGNORE"
}
);
It's like an own customization of ajax request for updating a cell.