【问题标题】:printing json object by ajax code in jsp在jsp中通过ajax代码打印json对象
【发布时间】:2016-06-21 11:02:05
【问题描述】:

我正在尝试在客户端 (.jsp) 中通过 ajax 在对象上打印一个 js .. 但它告诉我发生了错误 .. 这是我的代码 在小服务程序中

response.setContentType("application/json;charset=utf-8");
    JSONObject json = null;
    try {
        json = new JSONObject();
        json.put("json", "1213");
    } catch (JSONException e) {
        e.printStackTrace();
    }
    PrintWriter pw = response.getWriter(); 
    pw.print(json.toString());
    pw.close();

在jsp中

$(document).ready(function(){
    $.ajax({

        url : "Server",
        dataType : 'json',
        error : function() {

            alert("Error Occured");
        },
        success : function(data) {
            alert(data);

        }
    });
});

有什么建议吗??

【问题讨论】:

  • 什么样的错误?您应该使用error : function(that, e) {console.log(e);}),然后查看浏览器的javascript控制台。
  • 这里是“服务器响应状态为 404(未找到)”
  • 很明显你的请求路径是错误的
  • 我改了 tp"localhost:8080/startNew/Server" 然后出现"解析错误
  • 你为什么要在警报中打印 json?最好使用 console.log(data)

标签: java jquery json ajax jsp


【解决方案1】:

请尝试以下代码,

$(document).ready(function(){
        $.ajax({

            url : "PlaceCorrectPath",
            dataType : 'json',
            error : function() {

                alert("Error Occured");
            },
            success : function(data) {
               var val= $.parseJSON(data);
        console.log(val.YourKeyName)

            }
        });
    });

【讨论】:

  • 请让我知道错误并确保成功函数返回一些 JSON 数据作为响应
  • Uncaught SyntaxError: Unexpected token S
  • 尝试将 JSON 数据解析为 $.parseJSON(data.d)
  • 请在成功函数中使用 alert(JSON.stringify(data)) 并让我知道您得到的响应
  • 名为 startNew 的项目
猜你喜欢
  • 2016-06-22
  • 1970-01-01
  • 2011-10-05
  • 1970-01-01
  • 2016-12-30
  • 2012-12-14
  • 1970-01-01
  • 1970-01-01
  • 2021-05-24
相关资源
最近更新 更多