Почему моя форма jQuery Bootstrap не передает чистый JSON в службу REST? - PullRequest
0 голосов
/ 11 мая 2018

У меня есть веб-страница, созданная с помощью Bootstrap и jQuery.

Модальное диалоговое окно отображает простую форму. При нажатии кнопки он отправляет содержимое формы в формате JSON в мой веб-сервис REST.

Вот модальное диалоговое окно ...

<!-- Modal -->
  <div class="modal fade" id="myModal" role="dialog">
    <div class="modal-dialog">

      <!-- Modal content-->
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal">&times;</button>
          <h4 class="modal-title">Create New User</h4>
        </div>
        <div class="modal-body">

          <form id="createForm">
              <p><input id="firstName" type="text"/>
              <p><input id="lastName" type="text"/>
              <p><input id="emailAddr" type="text"/>
              <button id = "doCreateButton" class="btn btn-primary" type="submit">Submit</button>
              <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
          </form>

        </div>
    </div>
  </div>

Вот скрипт, который выполняет POST ...

<script>
    $(function() {
        //twitter bootstrap script
        $("#doCreateButton").click(function() {
            $.ajax({
                type : "POST",
                url : "http://localhost:8080/myapp/json/user/create",
                data : JSON.stringify( $('#createForm').serialize()),
                success : function(msg) {
                    $("myModal").modal('hide');
                },
                error : function() {
                    alert("failure");
                },
                done : function(e) {
                    console.log("DONE");
                    $("myModal").modal('hide');
                }
            });
        });
    });
</script>

Проблема в том, что текст, отправляемый веб-службе REST, заключается в следующем ...

%22%22=

Что я делаю не так?

UPDATE:

Ниже приведен фрагмент REST-сервиса, созданного с помощью Spring Web @RestController ...

import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/.../

@RestController
public class WebRestController {

    @Autowired
    UserService userService;

    public WebRestController() {
        // TODO Auto-generated constructor stub
    }

    @RequestMapping(value = "/json/user/create", method = RequestMethod.POST)
    public ResponseEntity<String> createUser(@RequestBody String json) throws Exception {

        /* ... do stuff ... */

        return new ResponseEntity<String>(replyObj.toJSONString(), HttpStatus.OK);  
    }   

Ответы [ 3 ]

0 голосов
/ 11 мая 2018

Во-первых, JSON.stringify( $('#createForm').serialize()); возвращает

""firstName=Robert&lastName=Hume&emailAddr=RobertHume%40gmail.com""

Вы можете отправлять данные JSON следующим образом:

var frm = $("#createForm").serializeArray();
      var obj = {};
      for (var a = 0; a < frm.length; a++) {
         obj[frm[a].name] = frm[a].value;
      }
        var jsonData = JSON.stringify(obj);

jsonData переменная теперь json

"{"firstName":"Robert","lastName":"Hume","emailAddr":"RobertHume@gmail.com"}"

Вот запрос Ajax.

<script>
    $(function() {
        //twitter bootstrap script
        $("#doCreateButton").click(function() {
            $.ajax({
                type : "POST",
                url : "http://localhost:8080/myapp/json/user/create",
                data : jsonData, //sending here..
                success : function(msg) {
                    $("myModal").modal('hide');
                },
                error : function() {
                    alert("failure");
                },
                done : function(e) {
                    console.log("DONE");
                    $("myModal").modal('hide');
                }
            });
        });
    });
</script>

Наконец, на стороне сервера вы должны перехватить @RequestBody UserRequest userRequest, создав класс dto запроса, как показано ниже.

public class UserRequest{
    String    firstName;
    String    lastName;
    String    emailAddr;

      //getter
      //setter

}
0 голосов
/ 13 мая 2018

Спасибо за помощь всем.В конце концов, у меня получилось так:

$(function() {
    //twitter bootstrap script
    $("#doCreateButton").click(function() {

        var formData = {
                  firstName:$('#firstName').val(),
                  lastName:$('#lastName').val(),
                  emailAddr:$('#emailAddr').val()
        };
        var sJSON = JSON.stringify(formData);
        alert( sJSON );
        $.ajax({
            type : "POST",
            url : "http://localhost:8080/myapp/json/user/create",
            data : sJSON,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success : function(msg) {
                $("#thanks").html(msg)
            },
            error : function() {
                alert("failure");
            },
            done : function(e) {
                console.log("DONE");
                $("myModal").modal('hide');
            }
        });
    });
});
0 голосов
/ 11 мая 2018
         var formData= $('#createForm').serialize()  ;   
         $.ajax({
                    type : "POST",
                    url : "http://localhost:8080/myapp/json/user/create",
                    data :  {formData:formData},
                    dataType: 'json',
                    success : function(msg) {
                        $("myModal").modal('hide');
                    },
                    error : function() {
                        alert("failure");
                    },
                    done : function(e) {
                        console.log("DONE");
                        $("myModal").modal('hide');
                    }
              });

Вы можете попробовать это.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...