发送JSON数据与jQuery [英] Send json data with jquery

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

问题描述

为什么下面发送的数据为code?市=莫斯科和放大器;年龄= 25,而不是JSON格式

  VAR ARR = {城市:'莫斯科',年龄:25};
$阿贾克斯(
   {
        网址:Ajax.ashx
        键入:POST,
        数据:ARR,
        数据类型:JSON,
        异步:假的,
        成功:函数(MSG){
            警报(味精);
        }
    }
);
 

解决方案

由于您没有指定没有要求的内容类型,也不是正确的JSON请求。下面就来发送JSON请求的正确方法:

  VAR ARR = {城市:'莫斯科',年龄:25};
$阿贾克斯({
    网址:Ajax.ashx,
    键入:POST,
    数据:JSON.stringify(ARR)
    的contentType:应用/ JSON的;字符集= UTF-8,
    数据类型:JSON,
    异步:假的,
    成功:函数(MSG){
        警报(味精);
    }
});
 

旅游注意:

  • JSON.stringify的用法方法为JavaScript对象转换成JSON字符串是本地和内置于现代浏览器。如果你想支持旧的浏览器,你可能需要包括 json2.js
  • 指定使用的contentType 属性,以指示服务器发送一个JSON请求的意图,要求的内容类型
  • 数据类型:JSON属性用来从服务器期待的回应类型。 jQuery是智能足够的猜到的从服务器上它内容类型响应头。所以,如果你有哪些方面或多或少的HTTP协议,并与响应内容类型的Web服务器:应用程序/ JSON 您的要求的jQuery会自动解析响应转换为JavaScript物体插入成功回调,这样你就不需要指定的dataType 属性。

事情要小心:

  • 您拨打什么改编不是数组。它与性质的JavaScript对象(年龄)。数组在JavaScript中表示与<​​code> [] 。例如 [{城市:'莫斯科',年龄:25},{城市:巴黎,年龄:30}] 2的对象数组

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

Things to notice:

  • 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.

Things to be careful about:

  • 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.

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

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