Javascript 使用 jQuery 发送 JSON 数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6587221/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 22:23:19  来源:igfitidea点击:

Send JSON data with jQuery

javascriptjqueryajax

提问by Neir0

Why code below sent data as City=Moscow&Age=25instead of JSON format?

为什么下面的代码发送数据City=Moscow&Age=25而不是 JSON 格式?

var arr = {City:'Moscow', Age:25};
$.ajax(
   {
        url: "Ajax.ashx",
        type: "POST",
        data: arr,
        dataType: 'json',
        async: false,
        success: function(msg) {
            alert(msg);
        }
    }
);

回答by Darin Dimitrov

Because you haven't specified neither request content type, nor correct JSON request. Here's the correct way to send a JSON request:

因为您既没有指定请求内容类型,也没有指定正确的 JSON 请求。以下是发送 JSON 请求的正确方法:

var arr = { City: 'Moscow', Age: 25 };
$.ajax({
    url: 'Ajax.ashx',
    type: 'POST',
    data: JSON.stringify(arr),
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    async: false,
    success: function(msg) {
        alert(msg);
    }
});

Things to notice:

注意事项:

  • Usage of the JSON.stringifymethod to convert a javascript object into a JSON string which is native and built-into modern browsers. If you want to support older browsers you might need to include json2.js
  • Specifying the request content type using the contentTypeproperty in order to indicate to the server the intent of sending a JSON request
  • The dataType: 'json'property is used for the response type you expect from the server. jQuery is intelligent enough to guessit from the server Content-Typeresponse header. So if you have a web server which respects more or less the HTTP protocol and responds with Content-Type: application/jsonto your request jQuery will automatically parse the response into a javascript object into the successcallback so that you don't need to specify the dataTypeproperty.
  • 使用该JSON.stringify方法将 javascript 对象转换为 JSON 字符串,该字符串是原生的并内置于现代浏览器中。如果你想支持旧浏览器,你可能需要包含json2.js
  • 使用contentType属性指定请求内容类型,以便向服务器指示发送 JSON 请求的意图
  • dataType: 'json'属性用于您期望从服务器获得的响应类型。jQuery 足够聪明,可以从服务器响应头中猜测Content-Type。因此,如果您有一个 Web 服务器,它或多或少地遵守 HTTP 协议并响应Content-Type: application/json您的请求,jQuery 会自动将响应解析为 javascript 对象到success回调中,这样您就不需要指定dataType属性。

Things to be careful about:

需要注意的事项:

  • What you call arris not an array. It is a javascript object with properties (Cityand Age). Arrays are denoted with []in javascript. For example [{ City: 'Moscow', Age: 25 }, { City: 'Paris', Age: 30 }]is an array of 2 objects.
  • 你所说arr不是数组。它是一个具有属性 (CityAge)的 javascript 对象。数组[]在 javascript中用 表示。例如[{ City: 'Moscow', Age: 25 }, { City: 'Paris', Age: 30 }]是一个包含 2 个对象的数组。

回答by lonesomeday

Because by default jQuery serializes objects passed as the dataparameter to $.ajax. It uses $.paramto convert the data to a query string.

因为默认情况下,jQuery 序列化作为data参数传递给$.ajax. 它用于$.param将数据转换为查询字符串。

From the jQuery docs for $.ajax:

来自 jQuery 文档$.ajax

[the dataargument] is converted to a query string, if not already a string

[data参数] 转换为查询字符串,如果还不是字符串

If you want to send JSON, you'll have to encode it yourself:

如果你想发送 JSON,你必须自己编码:

data: JSON.stringify(arr);

Note that JSON.stringifyis only present in modern browsers. For legacy support, look into json2.js

请注意,JSON.stringify它仅存在于现代浏览器中。对于遗留支持,请查看json2.js

回答by Aram Kocharyan

I wrote a short convenience function for posting JSON.

我写了一个简短的方便函数来发布 JSON。

$.postJSON = function(url, data, success, args) {
  args = $.extend({
    url: url,
    type: 'POST',
    data: JSON.stringify(data),
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    async: true,
    success: success
  }, args);
  return $.ajax(args);
};

$.postJSON('test/url', data, function(result) {
  console.log('result', result);
});

回答by Amrit

You need to set the correct content type and stringify your object.

您需要设置正确的内容类型并字符串化您的对象。

var arr = {City:'Moscow', Age:25};
$.ajax({
    url: "Ajax.ashx",
    type: "POST",
    data: JSON.stringify(arr),
    dataType: 'json',
    async: false,
    contentType: 'application/json; charset=utf-8',
    success: function(msg) {
        alert(msg);
    }
});

回答by picus

It gets serialized so that the URI can read the name value pairs in the POST request by default. You could try setting processData:false to your list of params. Not sure if that would help.

它被序列化,以便 URI 可以默认读取 POST 请求中的名称值对。您可以尝试将 processData:false 设置为您的参数列表。不确定这是否有帮助。