【问题标题】:POST JSON with AJAX not working使用 AJAX 的 POST JSON 不起作用
【发布时间】:2014-06-05 09:25:27
【问题描述】:

我一直无法使用 AJAX 将 JSON 数据发布到我的 Web 服务器。我查看了类似的主题并尝试了解决方案,但到目前为止没有任何效果。 How to send a JSON object using html form data

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
    $("#myForm").submit(function() {
//document.writeln("hello");
    var formData = JSON.stringify($("#myForm").serializeArray());
    //$('#result').text(JSON.stringify($('form').serializeObject()));
    $.ajax({
      type: 'POST',
      url: "http://localhost:8080/student-web/students/create",
      data: formData,
      success: function(){},
      dataType: 'json',
      contentType : 'application/json',
      processData: false
   `    });
   });
});

</script>
</head>

<body>
<h2>Form</h2>
<form  method="post" name="myForm">
Username:<input type="text" name="username" maxlength="12" size="12"/> <br/>
password:<input type="text" name="password" maxlength="36" size="12"/> <br/>

<p><button name="submit" onclick="submitform()">SUBMIT</button></p>
</form>

AJAX 没有执行,但我不知道为什么。我正在使用 RESTful Web 服务,当我卷曲帖子时,它可以工作:

curl -k -v -H "Content-Type: application/json" -X PUT -T "test" http://localhost:8080/student-web/students/create

在测试文件中是:

{"username":"hi","password":"bye"}    

RESTful Web 服务本身:

@RequestMapping(value = "/students/create", method = RequestMethod.POST)
@ResponseBody
public void insertStudent(@RequestBody Student student) {
    studentService.insertStudent(student);
}

我还创建了一个 applicationContext.xml,它允许 .jsp 页面和 json:

 <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  <property name="prefix" value="/WEB-INF/pages/" />
  <property name="suffix" value=".jsp" />
 </bean>
 <mvc:annotation-driven/>     

有人知道如何解决这个问题吗?提前致谢。

【问题讨论】:

  • 您使用form name 作为id 的表单的id 在哪里。为表单指定 id 并使用它。
  • 我改了并在表单中添加了id,但还是没有执行。 &lt;form method="post" id="myForm" name="myForm"&gt;

标签: jquery ajax json rest


【解决方案1】:

我在这里使用您的代码创建了一个 Fiddle,ajax 工作正常,请参见此处

http://jsfiddle.net/jF3eD/1/

$("#myForm").submit(function() { 
var formData = JSON.stringify($("#myForm").serializeArray());

$.ajax({     
  url: "/student-web/students/create",
  type: "POST",
  data: formData,
  success: function(){},
  dataType: 'json',
  contentType : 'application/json',
  processData: false
   });
});

如果这不能解决您的问题,请提供有关您的问题的更多信息。

【讨论】:

    猜你喜欢
    • 2019-01-26
    • 1970-01-01
    • 2012-06-24
    • 2016-04-17
    • 1970-01-01
    • 2012-05-12
    • 1970-01-01
    • 2012-05-31
    • 2016-11-05
    相关资源
    最近更新 更多