使用 jQuery 发送 JSON 数据 [英] Send JSON data with jQuery

查看:57
本文介绍了使用 jQuery 发送 JSON 数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

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

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

注意事项:

  • 使用 JSON.stringify 方法将 javascript 对象转换为 JSON 字符串,该字符串是原生的并内置于现代浏览器中.如果你想支持旧浏览器,你可能需要包含 json2.js
  • 使用 contentType 属性指定请求内容类型,以便向服务器表明发送 JSON 请求的意图
  • dataType: 'json' 属性用于您期望从服务器获得的响应类型.jQuery 足够智能,可以从服务器 Content-Type 响应头猜测它.因此,如果您有一个 Web 服务器或多或少地遵守 HTTP 协议并使用 Content-Type: application/json 响应您的请求,jQuery 将自动将响应解析为一个 javascript 对象到 success 回调,这样您就不需要指定 dataType 属性.
  • 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
  • The dataType: 'json' property is used for the response type you expect from the server. jQuery is intelligent enough to guess it from the server Content-Type response header. So if you have a web server which respects more or less the HTTP protocol and responds with Content-Type: application/json to your request jQuery will automatically parse the response into a javascript object into the success callback so that you don't need to specify the dataType property.

注意事项:

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

这篇关于使用 jQuery 发送 JSON 数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆