简体   繁体   中英

Sending JSON having dynamic values in POST body request

New to Javascript and had a basic query

For a POST AJAX request , I need to send following data in JSON format in the body parameter, however the longitude, latitude and radius values are dynamic, ie will be fed based on current location.

{
  "inGeoFence" : {
    "gpsCircle" : {
      "longitude": 122.2620,
      "latitude": 37.4996,
      "radius": 180000
    }
  }
}

The static way to write this is

 "data": "{\r\n  \"inGeoFence\" : {\r\n    \"gpsCircle\" : {\r\n      \"longitude\": 77.348235,\r\n      \"latitude\": 28.533938,\r\n      \"radius\": 100\r\n    }\r\n  }\r\n}\r\n"

Above data works fine since all are static values and a string is formed.

Can you please suggest me to write the same JSON so that dynamic values can be fed. Also what is the best/proper way to send JSON?

Thanks

Just construct JS object and that stringify it:

"data": JSON.stringify({
    inGeoFence: {
        gpsCircle: {
            longitude: getLong(),
            latitude: getLat(),
            radius: getRadius()
        }
    }
});

You can also send data as JS object and in server side read it as array:

$.ajax({
     data: {
      inGeoFence: {
        gpsCircle: {
          longitude: $('#long').val(),
          latitude: $('#lat').val(),
          radius: $('#radius').val()
        }
      }
    }
});

[server side, e.g. PHP]
$_POST['inGeoFence']['gpsCircle']['longitude']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM