How do I force a Coldfusion cfc to output numeric data over JSON as a string?

左心房为你撑大大i 提交于 2019-12-01 19:24:15
Henry

use parseInt() in JS. Kindda like your solution 1, but this is easier than you think.

$('#pagelink').attr("href") = "page.cfm?id=" + parseInt(result.ID, 10);

CF serializes any integer like 123 into "123.0" by default, but usually it doesn't matter in typeless language like JS, or CF for the matter.

The default behavior of SerializeJSON() (what remote function uses) cannot be overridden, but if you like, you can use one of the 3rd party JSON library from www.riaforge.org

p.s. Even if you browse to "something.cfm?id=123.0", URL.id is just a numeric value in CF that EQ to 123. Although your URL looks a little weird, if it is posting to CF, it'll still work.

Sergii

It's a known SerializeJSON() bug/feature. See this answer for possible workaround.

As an aside, for when you'd rather use solution 2) "I could force Coldfusion to send the number as a string", for instance when using a plugin that expects strings like dataTable and not wanting to touch the client code...

Just trying to force the number or string representing a number like below will not work :

Test["caseSensitiveName"] = "#numericString#";

But adding a leading space will force the JSON string type :

Test["caseSensitiveName"] = " #numericString#";

Hack hack hack, but can come in handy.

2) I could force Coldfusion to send the number as a string.

Are you doing any math with the id? Probably not. As far as your jquery is concerned, this is a string that contains only numbers, not an integer. Treat it as such.

Coming at it from another angle, if you control the back end too, you could try forcing ColdFusion to serialize the number as an integer, by using javaCast("int", someIntegerThatColdFusionThinksIsAFloat).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!