简体   繁体   中英

How to create and send JSON from client side

I have a web application. On the client side I basically need to get the values of some fields and turn them into JSON and then send them to the server in an AJAX kind of way.(asynchronous)

How would you do that? I also am using jQuery

If you want to create JSON (also called stringifying) on the client side, you can use the stringifier from json.org. More details about its use here .

You would then use your normal jQuery.ajax(...) like so:

function sendJSON(dataToStringify) {
   var stringifiedData = JSON.stringify(dataToStringify);

   jQuery.ajax({
      url: 'http://some.url.here',
      data: {stringified: stringifiedData},
      success: function(data) {
         //code to handle successful AJAX post
      },
      error(XMLHttpRequest, textStatus, errorThrown) {
         //code to handle errors
      }
   });
}

json2.js allows you to convert JavaScript objects to JSON representations using the JSON.stringify() function.

$.ajax() will allow you to then pass your string as a query parameter to your server side.

Quick example to tie them both together:

$.ajax({
  url: '/someurl',
  data: { json: JSON.stringify(myData) }
});

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