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

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

推荐答案

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

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);
    }
});

注意事项:

  • Usage of the JSON.stringify method 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 contentType property in order to indicate to the server the intent of sending a JSON request
  • dataType: 'json'属性用于您期望从服务器获得的响应类型.jQuery足够智能,可以从ServerContent-Type响应头中删除它.因此,如果您有一个或多或少遵守HTTP协议的web服务器,并以Content-Type: application/json响应您的请求,jQuery将自动将响应解析为success回调中的javascript对象,这样您就不需要指定dataType属性.

注意事项:

  • 你所说的arrnot an array.它是一个具有属性(CityAge)的javascript对象.数组在javascript中用[]表示.例如,[{ City: 'Moscow', Age: 25 }, { City: 'Paris', Age: 30 }]是2个对象的array.

Jquery相关问答推荐

无法通过单击从元素获取数据

如何在不使用点击事件 bootstrap 程序模式的情况下使用弹出窗口 bootstrap 程序显示用户详细信息?

无限滚动jQuery插件

如何在 bootstrap 模式关闭并重新打开时重置 bootstrap 模式?

.slice(0) 在这里有什么意义?

使用 bootstrap-datepicker 检测对选定日期的更改

如何正确卸载/销毁 VIDEO 元素

Twitter Bootstrap alert 可以淡入淡出吗?

谷歌图表重绘/zoom 窗口调整大小

Codemirror 编辑器在单击之前不会加载内容

根据弹出框相对于窗口边缘的 X 位置更改 Bootstrap 弹出框的位置?

专业的基于 jQuery 的 Combobox 控件?

jQuery.extend 和 jQuery.fn.extend 的区别?

如何使用 requirejs 使 jQuery 插件可加载

将打开/关闭图标添加到 Twitter Bootstrap 可折叠项(手风琴)

jQuery、复选框和 .is(":checked")

检测夹点的最简单方法

将数据发布到 JsonP

使用 jQuery 和 CSS 将数字转换为星级显示

在页面加载之间保持变量