如何使用 JQuery 发布 JSON 数据? [英] How can I use JQuery to post JSON data?

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

问题描述

我想将 Json 发布到同一服务器上的 Web 服务.但我不知道如何使用 JQuery 发布 Json.我已尝试使用此代码:

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

但是使用此 JQuery 代码,数据不会在服务器上以 Json 形式接收.这是服务器上的预期数据:{"name":"jonas"} 但使用 JQuery 服务器接收 name=jonas.或者换句话说,它是urlencoded"数据而不是 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 格式而不是 urlencoded 格式发布数据?还是我必须使用手动 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 使用 $.param 来序列化对象转换成名称-值对.

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天全站免登陆