How to send int parameters using jquery

I am creating a web service that will link to a webpage using jquery. I want to create my web service so that it is type-safe without the need for server-side conversions.

How can I make an ajax call from the client side using jquery on a server that expects an int value parameter.

Edit: I realized that this is not possible. I program the server side using C #. the web service currently supports both client side calls (js) and other utilities (other C # programs). The simplest solution I can think of right now is to copy the methods and change their signature to a string, then convert the data types and call the methods, this time with the correct data types.

Is there any .net 4 attribute that I can decorate with my method that does this automatically?

thank

+3
source share
4 answers

I'm afraid you can’t. All parameters sent with the request have a type string.

You can send parameters as JSON encoded.

Assuming Object

{"int":1}

urlencoded it

%7B%22int%22%3A1%7D

Send request http://domain.org/params=%7B%22int%22%3A1%7D

on domain.org decodes it:

$params=json_decode($_GET['params']);

And you will see that the type is still integer:

echo gettype($params->int);

But this is somehow also a conversion from the server (because you need to decode JSON).

As for the comment below, here is an example that shows that this is not a pig with lipstick, try and see if the types persist:

<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>

Conclusion:

object(stdClass)#1 (4) {
  ["pig"]=>
  int(1)
  ["cow"]=>
  float(2.2)
  ["duck"]=>
  string(6) "donald"
  ["rabbit"]=>
  object(stdClass)#2 (1) {
    ["ears"]=>
    int(2)
  }
}

, , , JSON "" .

+7

int , .

ints, script.php?id=2

$.get('script.php?id=2', function(data) {
  $('.result').html(data);
  alert('Load was performed.');
});
+3

, . .

, , int, float - JS- ( parseInt(), parseFloat()...), , - , , (, , )

+3

, . , - . , PHP - : id = 1 int, , ruby ​​ , int.

, , -, javascript, - , , . , , .

+1

Source: https://habr.com/ru/post/1786623/


All Articles