You are not logged in.
Pages: 1
Hi,
In my web application (TMVCApplication), I'd like to send a JSON object to my view, who contains a string with a single quote:
procedure TWebApp.Test(var Scope: Variant);
var
aSomeText: RawUTF8;
aVarRes: Variant;
begin
aSomeText := 'Some text with single quote here '' and that''s it.';
TDocVariant.New(aVarRes);
TDocVariantData(aVarRes).AddValue('Display', aSomeText);
_ObjAddProps(['test', aVarRes], Scope);
end;
The value of aVarRes in the debugger is:
'{"Display":"Some text with single quote here '' and that''s it."}'
In the view I have this in my script:
<script type="text/javascript">
var aTest = '{{{Scope.test}}}';
alert(aTest);
</script>
and I get:
<script type="text/javascript">
var aTest = '{"Display":"Some text with single quote here ' and that's it."}';
alert(aTest);
</script>
Which obviously raise an error.
If I try a string replace to replace all '' by \'' (the escape char in JS) like this before passing it to my variant:
aSomeText := StringReplace(aSomeText, '''', '\''', [rfReplaceAll]);
It seem that the char \ is escaped automatically like this:
value of "aSomeText" is: 'Some text with single quote here \'' and that\''s it.'
value of "aVarRes" is: '{"Display":"Some text with single quote here \\'' and that\\''s it."}'
Which obviously fail too..
edit:
and if I do this it work as expected: (but I can't in my use case build all the JSON by hand)
aSomeText := '{"Display":"Some text with single quote here \'' and that\''s it."}';
_ObjAddProps(['test', aSomeText], Scope);
I've tried a few others way but couldn't get it to work.
What would be the best way for me to achieve this ?
Thanks for your time !
Last edited by StxLog (2019-02-04 12:51:59)
Offline
Oh great I didn't knew there was such helper. It work as expected thanks for your help !
This is what I ended-up with:
Delphi:
procedure TWebApp.Test(var Scope: Variant);
var
aSomeText: RawUTF8;
aVarRes: Variant;
begin
aSomeText := 'Some text with single quote here '' and that''s it.';
TDocVariant.New(aVarRes);
TDocVariantData(aVarRes).AddValue('Display', aSomeText);
_ObjAddProps(['test', aVarRes], Scope);
end;
JS:
<script type="text/javascript">
var aTest = JSON.parse({{{JSONQuote Scope.test}}});
alert(JSON.stringify(aTest));
</script>
Offline
Pages: 1