I am building a web service that will communicate with a web page using jquery. I want to build my webservice so it is type safe, without the need to perform conversions on the server side.
How can I issue an ajax call from the client side, using jquery to the server that's expecting an int value parameter.
Edit: I understood that this is not possible. I am programming the server side with c#. currently the web service supports both calls from client side (js) and other utilities (other c# programs). The simplest solution I can currently think of is copying the methods and change their signature to string, then convert the datatypes and call the methods, this time with the correct data types.
Is there any .net 4 attribute that I can decorate my method that performs this automatically?
Thank you
I'm afraid you can't. All parameters send with an request are of type string.
You could send the parameters as encoded JSON.
Assuming an object
{"int":1}
urlencoded it is
%7B%22int%22%3A1%7D
Send a request to http://domain.org/params=%7B%22int%22%3A1%7D
on domain.org decode it:
$params=json_decode($_GET['params']);
And you will see that the type is still integer:
echo gettype($params->int);
But this somehow also is a serverside conversion(because you need to decode the JSON).
Regarding to the comment beyond, here an example that shows that it's not a pig with lipstick, try it and see if the types are preserved:
<html>
<head>
<title>Test</title>
<script type="text/javascript">
<!--
function request()
{
var obj={
"pig":1,
"cow":2.2,
"duck":'donald',
"rabbit":{"ears":2}
};
location.replace('?params='+encodeURIComponent(JSON.stringify(obj)));
}
//-->
</script>
</head>
<body>
<input type="button" onclick="request()" value="click">
<pre><?php
if(isset($_GET['params']) && $params=json_decode($_GET['params']))
{
var_dump($params);
}
?>
</pre>
</body>
</html>
Output:
object(stdClass)#1 (4) {
["pig"]=>
int(1)
["cow"]=>
float(2.2)
["duck"]=>
string(6) "donald"
["rabbit"]=>
object(stdClass)#2 (1) {
["ears"]=>
int(2)
}
}
That's not bad in my mind, that's simply what JSON has been "invented" for, interchange data between applications.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With