我如何使用jQuery张贴JSON数据? [英] How can I use JQuery to post JSON data?

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

问题描述

我要留言JSON来的Web服务在同一台服务器上。但我不知道如何使用jQuery后JSON。我曾尝试与该code:

I would like to post Json to a web service on the same server. But I don't know how to post Json using JQuery. I have tried with this code:

$.ajax({
    type: 'POST',
    url: '/form/',
    data: {"name":"jonas"},
    success: function(data) { alert('data: ' + data); },
    contentType: "application/json",
    dataType: 'json'
});

但用c中的数据没有收到为JSON在服务器上的这个jQuery $ C $。这是在服务器上预期的数据: {名:乔纳斯} ,但使用JQuery服务器接收名称=乔纳斯。或者换句话说,它的urlen codeD的数据和不JSON。

But using this JQuery code the data is not received as Json on the server. This is the expected data at the server: {"name":"jonas"} but using JQuery the server receive name=jonas. Or in other words, it's "urlencoded" data and not Json.

有没有办法发布使用JQuery的JSON格式,而不是urlen codeD数据的数据?还是我必须使用手工Ajax请求?

Is there any way to post the data in Json format instead of urlencoded data using JQuery? Or do I have to use a manual ajax request?

推荐答案

您正在传递一个对象,没有的JSON字符串。当你传递一个对象,jQuery使用 $。参数 连载对象到名称 - 值对

You're passing an object, not a JSON string. When you pass an object, jQuery uses $.param to serialize the object into name-value pairs.

如果您通过数据作为一个字符串,它不会被序列化:

If you pass the data as a string, it won't be serialized:

$.ajax({
    type: 'POST',
    url: '/form/',
    data: '{"name":"jonas"}', // or JSON.stringify ({name: 'jonas'}),
    success: function(data) { alert('data: ' + data); },
    contentType: "application/json",
    dataType: 'json'
});

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

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