无法将 JSON 对象提交到 JSP



我正在尝试将JSON对象发送到JSP进行解析。JavaScript代码为:

function sendData(field1, oper1, value1, field2, oper2, value2, field3, oper3, value3){
        var formData = {"field1":field1, "oper1":oper1, "value1":value1, "field2":field2, "oper2":oper2, "value2":value2, "field3":field3, "oper3":oper3, "value3":value3};
        $.post("<%=request.getRequestURL().toString()%>getInfo.jsp", {formData:formData}, function(response){alertHere(response)});
    }
function alertHere(){
        window.alert("Post Successful!")
    }
我的提交按钮是:
<input type="submit" value="SEARCH" name="submit" class="srchbutton" onclick="sendData(document.getElementById('field1').value, document.getElementById('oper1').value>

还有几个字段传递在JavaScript按钮点击,我只是不想张贴那么长的一行。

当我尝试在表单中发布文本数据时,我的web开发人员控制台会快速地闪烁到我的JSP的路径,然后消失。它太快了,看不到错误。如果没有数据,则帖子成功,因为$.post()中的alertHere函数被正确调用。我不确定我是否错过了什么

假设您在服务器端有一个servlet来处理从jsp页面发送的数据,您可以使用javascript创建一个伪类,然后将其解析为json,最后将其发送到服务器。例如:

javascript和jQuery

function SomeClass (){
  this.field1 = $("#field1").val();
  this.oper1 = $("#oper1").val();
  this.value1 = $("#value1").val();
  // etc. for every field you want to send
}

注意:我假设每个字段都有一个id。

function alertHere(){
   window.alert("Post Successful!")
}
jQuery和ajax
$("#someID").click(function(){
    event.preventDefault(); <-------- if you replace the submit button for a simple button,
                                      you don't need to do this.
    var formData = new  SomeClass();
    $.ajax({
      url:"ServletName", 
      data: JSON.stringify(formData), 
      dataType:"json",
    }).done(function(response){
         alertHere(response);
    });
});
html

<input type="submit" value="SEARCH" id="someID" name="submit" class="srchbutton">

尝试更改这行代码

$.post("<%=request.getRequestURL().toString()%>getInfo.jsp", {formData:formData}

$.post("<%=request.getRequestURL().toString()%>getInfo.jsp", {formData:Json.stringify(formData)}                         

不完全确定这是否可行,只是一个建议。

明白了。问题是我没有将"response"传递给成功函数,所以:

function alertHere(){
    window.alert("Post Successful!")
}

应该是:

function alertHere(response){
    window.alert("Post Successful!")
}

它可能是正确的张贴,但我没有得到成功,因为响应没有通过。

最新更新