如何从jQuery发送json数据?

时间:2013-04-05 15:31:12

标签: ajax json jsp

我正在尝试发送JSON字符串

var json = {"city":value1, "country":value2};
$.ajax({
    url : url,
    data : json,
    dataType : 'json',
    success : function(response) {
        alert(response);
    }
})

在我进行ajax调用的URL中,我没有得到如何获取此字符串值?我该怎么用request.getParameter?参数中的值应该是什么?

3 个答案:

答案 0 :(得分:3)

Ajax请求:

 var jsonObj= { jsonObj: [... your elements ...]};

    $.ajax({
        type: 'post',
        url: 'Your-URI',
        data: JSON.stringify(jsonObj),
        contentType: "application/json; charset=utf-8",
        traditional: true,
        success: function (data) {
            ...
        }
    });

在服务器端:

String city =    request.getParameter("city");

String country=    request.getParameter("country");

答案 1 :(得分:2)

这可能是一个坏主意,但已经完成了这项工作。感谢大家分享您的想法很难发送数据。我看到了@baadshah提出的所有建议答案,但我无法实现单一的答案。 :(。我重新分析了这个问题。

我的问题是我无法检索服务器端页面中的JSON数据,因为我可以访问其他元素。我的HTML页面有其中一个

  <input type = "text" name = "fname" class = "imp"/>

在我的JSP页面中,我可以使用

 String fname = request.getParameter("fname");

在被困了几个小时并且感到沮丧后,我想到了另一种方式。这是我找到的解决方案。如果我可以将JSON字符串与任何带有有效名称的输入标记组合在一起,就可以解决这个问题。下一刻我在脚本标签

中添加了这一行
$('input[name=hide]').val(json);
var dataToBeSent = $("form#hidden").serialize();

在HTML部分中,我添加了以下代码段。

<form name="hidden" id="hidden">
     <input type="hidden" name="hide"/>
</form>

这解决了我的问题。这可能不是最好的方法,但它完成了这项工作。

答案 2 :(得分:0)

type: "POST"

应该这样做。