【问题标题】:I get null when I pass JSON array with JQuery AJAX当我使用 JQuery AJAX 传递 JSON 数组时我得到 null
【发布时间】:2013-09-04 08:25:55
【问题描述】:

我遇到了 JQuery ajax 函数的问题。

我正在尝试通过如下所示的 ajax 发送一个简单的 json。

$.ajax({
            url: 'NewFile.jsp', 
            type: 'GET',
            data: {"datasource":"hello1", definition:[{val1:"hello3"}]},
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            async: false,
            success: function(msg) {
                alert("Successfully posted "+JSON.stringify(json));
            }
        });

问题是当我这样做时

System.out.println(request.getParameter("datasource")); 
System.out.println(request.getParameter("definition"));

在我的NewFile.jsp 中,第一个得到 hello1,第二个得到 null。

为什么我在第二个println() 中得到空值?

谢谢

【问题讨论】:

  • request.getParameter("definition[0][val1]") 可能包含预期值。
  • @SalmanA 你说的话就像一个魅力。谢谢。是否可以将定义数组作为 java 集合获取,因为我需要遍历该数组?或者是否可以将数据字段中的所有 json 作为我的 jsp 页面中的字符串以便与 gson 一起使用?
  • 你使用任何框架,例如struts吗?
  • 不,我不... :( @gjman2
  • 似乎 JSP 不像 PHP 那样解析查询字符串变量,例如 a[0]=foo&a[1]=bar。您可以将数组转换为逗号分隔的列表或以 JSON 格式“发布”数据并在服务器端对其进行解码。

标签: javascript jquery ajax json jsp


【解决方案1】:

在 ajax 对象内的 url 变量中,提供请求的完整 URL。像这样:

$.ajax({
            url: 'www.google.com/', 
            type: 'GET',
            data: {"datasource":"hello1", definition:[{val1:"hello3"}]},
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            async: false,
            success: function(msg) {
                alert("Successfully posted "+JSON.stringify(json));
            }
        });

此外,请始终确保您的对象字面量中有一个 failure 变量,以便您知道它发生了,但失败了。帮助调试。

【讨论】:

    猜你喜欢
    • 2021-08-22
    • 2017-03-15
    • 2014-01-09
    • 1970-01-01
    • 2015-05-15
    • 2015-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多