开发者

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开发者_JAVA百科 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) }
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜