【问题标题】:sending ajax call to server with json data使用 json 数据向服务器发送 ajax 调用
【发布时间】:2013-10-23 10:44:33
【问题描述】:

我是“jQuery ajax”的新手,我正在使用 ajax 将请求发送到服务器。我正在发送数据,即 no、name、class、age 作为正常参数。我的要求是,我想以 JSON 格式发送数据。我的代码是,

function fun1() {

    $.ajaxSetup({
        jsonp: null,
        jsonpCallback: null
    });

    $.ajax({
        type: 'POST',
        url: 'register.action',
        dataType: 'json',
        data: {
            no: document.getElementById("id1").value,
            name: document.getElementById("id2").value,
            clas: document.getElementById("id3").value,
            age: document.getElementById("id4").value    
        },    
        success: function (data) {    
            printStudentDetails(data);    
        },
        error: function () {
            alert("failure");
        }
    });

}

我的服务器端资源是java。

【问题讨论】:

  • 你的问题/问题是什么?
  • 您可能应该使用 POST 发送 json 数据 - 我什至不确定 GET 会对您的数据做什么。例如,它可能只编码:?no=JUNK&name=JUNK。另外,添加contentType: 'application/json'
  • 查看 Java JSONObject json.org/java 我假设您想将 java 对象呈现为 json
  • 正如 Blazes 所说:更改为 type: 'post'

标签: jquery ajax json


【解决方案1】:

试试这个:

$.ajaxSetup({
    jsonp: null,
    jsonpCallback: null
});

function fun1(){

    $.ajax({
        type: 'POST',
        url: 'register.action',
        dataType: 'json',
        data: {
            jsonData: JSON.stringify({
                no: $('#id1').val(),
                name: $('#id2').val(),
                clas: $('#id3').val(),
                age: $('#id4').val()
            }) 
        },    
        success: function (data) {    
            printStudentDetails(data);    
        },
        error: function () {
            alert("failure");
        }
    });

}

这将对您的服务器 url 进行 HTTP 发布,其中一个发布字段将被称为“jsonData”,其中将包含表单数据的 json 编码字符串值(您可以将其解码为数组/对象以进行操作/存储您的服务器)。

【讨论】:

  • 如何在服务器端解码这个 json 编码的字符串值。我在服务器端使用 java struts2。
  • 我不使用 java,我回答了你问题的 jquery/ajax 药水。在谷歌上搜索并找到this。您需要在您的 java 中定义 JSON 数据包含的内容的类定义,并使用此(示例)解码回数据:List<User> userList = (List<User>)JSON.deserialize(stringObject,List<User>.class); 其中“用户”是定义 json 数据结构的类。
猜你喜欢
  • 2011-09-17
  • 1970-01-01
  • 2012-01-09
  • 2013-10-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-22
  • 1970-01-01
相关资源
最近更新 更多