String with quotation marks from SpringMVC controller, not shown with javascript-jquery - javascript

I try to show data with jquery, sent from a controller of Spring MVC. The problem is the string have quotation marks from database, therefore, my code with javascript - jquery, not working.
For example, my string is (principal:"Carl Duvierts") in database, sending by the controller.
alert("${person.name}"); //not working

If the object you're using is already a string, you don't need the quotes around it in an alert.
//this will work
var stringWithQuotes = 'abc"de"fg';
alert(stringWithQuotes);//no quotation marks inside the parentheses
//The code you provided:
alert("${person.name}");
//will just alert the actual string '${person.name}', not what is referenced by the variable

Related

JSP attribute JSON object is dropping escape characters in Javascript

I have a server-side controller which is adding an attribute which is a Java object converted to JSON using Jackson:
ObjectMapper mapper = new ObjectMapper();
model.addAttribute("commentObj", mapper.writeValueAsString(commentObject);
My commentObject has a field "comments" which contains quotation marks (") that JSON needs to escape. When I do a simple print-out from the JSP of the commentObject, everything looks good:
[{"commentId":123,"comments": "this \"test\" is here"}]
As you see, the quotes get escaped properly (\").
My problem comes with the javascript on this page that also needs to access this object. So when I run the following:
<script>
var test = ${commentObj};
</script>
If I take a look at the 'test' var, the comments field now reads as follows:
"this "test" is here"
vs.
"this \"test\" is here"
This causes a problem because JSON.parse() will throw an error on 'test' because it is not properly formed JSON anymore.
So my question is, how do I manage to get my commentObj into a javascript object while keeping the escape characters so that I can JSON.parse it properly?
Sorry, written at the end of a long day while sick and only just realized now that the 'test' var ends up being a fully formed JS object. So I am able to use that.
That said, I still have the question of how that is happening? It seems to me that it should be coming in as a JSON string that I need to call JSON.parse on. Anyone have an explanation?

string.slice() not working on Server Side Javascript in ASPx

I am writing server side javascript code in aspx to pull out the 7 columns from CSV files which may or may not use quotes to enclose the data, depending on the file.
Currently, I am working on the code to remove the commas using javascript's string.sllice() for the first column, but is is returning an empty string.
Here is a sample line from the file. This is public info.
12/6/2017,8:30 AM,2013FA000060,In RE: the Support of: D.D.K. and A.P.C.,MH,Motion hearing,"Grill, Leo",State of Wisconsin,"Vesely, Tori A; Lawton, Mark David";
In working with my Regular expression based code for the first column, I have the correct expected string data for strTemp prior to the offending code:
12/6/2017,
Here is the code to remove the comma at the end:
cleanData = strTemp.slice(0, -1); // remove last 1 character
I have verified that strTemp is correct right before this statement is executed to make sure the string var assignments are not the problem (as seen above).
The expected result should be strTemp data without the comma at the end:
12/6/2017
I receive no errors. Just an empty string.
OK, so it looks like the data coming from the regular expression execute is not a string. Once I cast it to string it worked
cleanData = strTemp.toString().slice(0, -1);
I really do NOT like working with weakly typed languages!!

Error Parsing JSON with escaped quotes

I am getting the following json object when I call the URL from Browser which I expect no data in it.
"{\"data\":[], \"SkipToken\":\"\", \"top\":\"\"}"
However, when I tried to call it in javascript it gives me error Parsing Json message
dspservice.callService(URL, "GET", "", function (data) {
var dataList = JSON.parse(data);
)};
This code was working before I have no idea why all of a sudden stopped working and throwing me error.
You say the server is returning the JSON (omitting the enclosing quotes):
{\"data\":[], \"SkipToken\":\"\", \"top\":\"\"}
This is invalid JSON. The quote marks in JSON surrounding strings and property names should not be preceded by a backslash. The backslash in JSON is strictly for inserting double quote marks inside a string. (It can also be used to escape other characters inside strings, but that is not relevant here.)
Correct JSON would be:
{"data":[], "SkipToken":"", "top":""}
If your server returned this, it would parse correctly.
The confusion here, and the reports by other posters that it seems like your string should work, lies in the fact that in a simple-minded test, where I type this string into the console:
var x = "{\"data\":[], \"SkipToken\":\"\", \"top\":\"\"}";
the JavaScript string literal escaping mechanism, which is entirely distinct from the use of escapes in JSON, results in a string with the value
{"data":[], "SkipToken":"", "top":""}
which of course JSON.parse can handle just fine. But Javascript string escaping applies to string literals in source code, not to things coming down from the server.
To fix the server's incorrectly-escaped JSON, you have two possibilities. One is to tell the server guys they don't need to (and must not) put backslashes before quote marks (except for quote marks inside strings). Then everything will work.
The other approach is to undo the escaping yourself before handing it off to JSON.parse. A first cut at this would be a simple regexp such as
data.replace(/\\"/g, '"')
as in
var dataList = JSON.parse(data.replace(/\\"/g, '"')
It might need additional tweaking depending on how the server guys are escaping quotes inside strings; are they sending \"\\"\", or possibly \"\\\"\"?
I cannot explain why this code that was working suddenly stopped working. My best guess is a change on the server side that started escaping the double quotes.
Since there is nothing wrong with the JSON string you gave us, the only other explanation is that the data being passed to your function is something other than what you listed.
To test this hypothesis, run the following code:
dspservice.callService(URL, "GET", "", handler(data));
function handler(data) {
var goodData = "{\"data\":[], \"SkipToken\":\"\", \"top\":\"\"}";
alert(goodData); // display the correct JSON string
var goodDataList = JSON.parse(goodData); // parse good string (should work)
alert(data); // display string in question
var dataList = JSON.parse(data); // try to parse it (should fail)
}
If the goodData JSON string can be parsed with no issues, and data appears to be incorrectly-formatted, then you have the answer to your question.
Place a breakpoint on the first line of the handler function, where goodData is defined. Then step through the code. From what you told me in your comments, it is still crashing during a JSON parse, but I'm willing to wager that it is failing on the second parse and not the first.
Did you mean that your JSON is like this?
"{\"data\":[], \"SkipToken\":\"\", \"top\":\"\"}"
Then data in your callback would be like this:
'"{\"data\":[], \"SkipToken\":\"\", \"top\":\"\"}"'
Because data is the fetched text content string.
You don't have to add extra quotes in your JSON:
{"data":[], "SkipToken":"", "top":""}

unterminated string literal in javascript

I have one string in my JSON. the value is To be Reviewed.
I am retrieving this string in my client side using data[i].status syntax. It fetches the correct value but when I send this syntax as paramter it gives unterminated string literal error on client side.
My code is:
onClick=test('"+data[i].product+"','"+data[i].status+"').
How can I send the string value in another function?
thanks in advance.
As you are appending variables you do not need the quotes around them, only the value you are assigning to the onClick parameter. Assuming your test function accepts two parameters, this should work:
onClick="test(data[i].product, data[i].status)"

Passing strings with Single Qoute from MVC Razor to JavaScript

This seems so simple it's embarrassing. However, the first question is when passing a value from the new ViewBag in MVC 3.0 (Razor) into a JavaScript block, is this the correct way to do it? And more importantly, where and how do you apply the proper string replacement code to prevent a single quote from becoming &#39 as in the resultant alert below?
Adding this into a single script block:
alert('#ViewBag.str') // "Hi, how's it going?"
Results in the following alert:
Razor will HTML encode everything, so to prevent the ' from being encoded to ', you can use
alert('#Html.Raw(ViewBag.str)');
However, now you've got an actual ' in the middle of your string which causes a javascript error. To get around this, you can either wrap the alert string in double quotes (instead of single quotes), or escape the ' character. So, in your controller you would have
ViewBag.str = "Hi, how\\'s it going?";
Another solution to use JSON string:
C#
ViewBag.str = "[{\"Text\":\"Hi, how's it going?\"}]";
Javascript
var j = #Html.Raw(ViewBag.str);
alert (j[0].Text);

Categories

Resources