简体   繁体   English

如何从客户端创建和发送JSON

[英]How to create and send JSON from client side

I have a web application. 我有一个Web应用程序。 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) 在客户端,我基本上需要获取某些字段的值并将它们转换为JSON,然后以AJAX方式将它们发送到服务器。(异步)

How would you do that? 你会怎么做? I also am using jQuery 我也在使用jQuery

If you want to create JSON (also called stringifying) on the client side, you can use the stringifier from json.org. 如果要在客户端创建JSON(也称为字符串化),可以使用json.org中的字符串化器。 More details about its use here . 关于它在这里使用的更多细节。

You would then use your normal jQuery.ajax(...) like so: 然后,您将使用正常的jQuery.ajax(...)如下所示:

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. json2.js允许您使用JSON.stringify()函数将JavaScript对象转换为JSON表示。

$.ajax() will allow you to then pass your string as a query parameter to your server side. $ .ajax()将允许您将字符串作为查询参数传递给服务器端。

Quick example to tie them both together: 将它们绑在一起的快速示例:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从我的休息服务发送一个json对象,以便我可以在客户端javascript解析 - How do I send a json object from my rest service so I can parse in out on the client side javascript 如何将 javascript 文件(其中包含多个函数)从服务器发送到客户端? - How to send a javascript file (with several functions in it) from the server to the client side? 如何限制从Json(客户端)检索的数据量? - How to limit number of data retrieved from Json (client side)? 如何将/ post JSON数组从客户端传递到服务器? - How to pass /post JSON array to the server from the client side? 将按钮从C#发送到客户端 - Send button from c# to client side 使用jqueries验证插件,如何从服务器端向客户端发送错误? - Using jqueries validation plugin, how to send an error from the server side to the client side? 如何以 GET 方法将数据从客户端发送到服务器端 - ajax - how to send data in GET method from client side to server side - ajax 如何在不使用处理程序的情况下使用ajax从客户端将文件发送到服务器端? - How to send file to server side from client side using ajax without using handler? 从服务器端向客户端节点发送数据 - Send data from server side to client side Node 如何解析一个JSON对象? (从服务器端到客户端…javascript) - How to parse a JSON object ? (From server-side to client-side…javascript)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM