我必须使用JQuery + Ajax发送JSON对象数据,这将由RestFulWebServices消耗。在后端,我使用的是hibernate(版本4)+ Maven(版本3)+ spring(版本4),MySql数据库和ApacheTopcat服务器(版本7)。但是我的JqueryAjax代码index.html客户端未通过服务器发送数据。请帮助我搜索,但它们在我的Jquery Ajax部分中没有错误。如果您有其他需要告诉我,我会过去这里。

form.html

<!DOCTYPE html>
<html lang="en">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
    $(document).ready(function(){
       alert("1");
      $("button").click(function(){
        alert("2");
        var custName = $('#custName').val();
        var custMobile = $('#custMobile').value;
        var custEmail = $('#custEmail').value;
        var custAddress = $('#custAddress').value;
        var JSONObject={"custName":custName, "custMobile": custMobile, "custEmail":custEmail,"custAddress":custAddress};
        /*
        var jsonData=JSON.stringify({
            "custName": "Navin1",
            "custMobile": "876532468",
            "custEmail": "abc@gmal.com",
            "custAddress": "BAnaore"
        });
        */
        var jsonData = JSON.stringify( JSONObject );
        $.ajax({
             url: "http://localhost:8080/HomeServiceProvider/customer/saveCustomer",
             type: "POST",
             dataType: "json",
             data: jsonData,
             contentType: "application/json; charset=utf-8",
             async: false,
             cache: false,
             processData:false,
         success: function(response){
            alert("scucess");
            alert(JSON.stringify(response));
         },
         error: function(err){
            alert("Fail");
            alert(JSON.stringify(err));
         }
    });

      });
    });
</script>
</head>
    <body>
        <form>
            <fieldset style="text-align:right; width:300px">
                <legend><b>Registration Form</b></legend>
                    Name <input type="text" id="custName" name="custName"/><br/>
                    Mobile No <input type="text" id="custMobile" name="custMobile"/><br/>
                    Email <input type="text" id="custEmail" name="custEmail"/><br/>
                    Address <input type="text" id="custAddress" name="custAddress"/><br/>
                <button>Save Data</button>
            </fieldset>
        </form>
    </body>
</html>

我的服务器网址是
http://localhost:8080/HomeServiceProvider/customer/saveCustomer

我的客户休息控制器是
CustomerRestController
@RestController
@RequestMapping("/customer")
public class CustomerRestController {

    private static Logger log = LogManager.getLogger(CustomerRestController.class);

    @Value("${msg.customeradded}")
    private String message;
    @Value("${msg.successcode}")
    private int code;

    @Autowired
    private CustomerService customerService;

    @RequestMapping(value = "/saveCustomer", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
    public @ResponseBody Status saveCustomer(@RequestBody Customer customer){
        try {
            customerService.saveCustomer(customer);
            return new Status(code, message);
        } catch (Exception e) {
            return new Status(0, e.toString());
        }
    }

    @RequestMapping(value="/getAllCustomer",method=RequestMethod.GET, headers="Accept=application/json")
    public @ResponseBody List<Customer> getAllCustomer(){
        List<Customer> customers = null;
        try {
            customers = customerService.getAllCustomer();
        log.info("Size:"+customers.size());
        log.info("customers:"+customers);
        } catch(Exception e) {
            e.printStackTrace();
        }
        return customers;
    }
}

MyCustomer类Customer.Java,用于通过Hibernate制作表
@Entity
@Table(name = "customer", catalog = "service4homes")
public class Customer implements java.io.Serializable {

    private Integer CId;
    private String custName;
    private String custMobile;
    private String custEmail;
    private String custAddress;

    public Customer() {
    }

    public Customer(String custName, String custMobile, String custAddress) {
        this.custName = custName;
        this.custMobile = custMobile;
        this.custAddress = custAddress;
    }

    public Customer(String custName, String custMobile, String custEmail,
            String custAddress) {
        this.custName = custName;
        this.custMobile = custMobile;
        this.custEmail = custEmail;
        this.custAddress = custAddress;
    }

    @Id
    @GeneratedValue(strategy = IDENTITY)
    @Column(name = "c_id", unique = true, nullable = false)
    public Integer getCId() {
        return this.CId;
    }

    public void setCId(Integer CId) {
        this.CId = CId;
    }

    @Column(name = "cust_name", nullable = false, length = 50)
    public String getCustName() {
        return this.custName;
    }

    public void setCustName(String custName) {
        this.custName = custName;
    }

    @Column(name = "cust_mobile", nullable = false, length = 13)
    public String getCustMobile() {
        return this.custMobile;
    }

    public void setCustMobile(String custMobile) {
        this.custMobile = custMobile;
    }

    @Column(name = "cust_email", length = 100)
    public String getCustEmail() {
        return this.custEmail;
    }

    public void setCustEmail(String custEmail) {
        this.custEmail = custEmail;
    }

    @Column(name = "cust_address", nullable = false, length = 300)
    public String getCustAddress() {
        return this.custAddress;
    }

    public void setCustAddress(String custAddress) {
        this.custAddress = custAddress;
    }

}

当我运行代码时,我得到的是
form.index数据

单击按钮后

最佳答案

$.ajax({

            url:urlName,

            type:"POST",

            contentType: "application/json; charset=utf-8",

            data: jsonString, //Stringified Json Object

            async: false,    //Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation

            cache: false,    //This will force requested pages not to be cached by the browser

            processData:false, //To avoid making query String instead of JSON

            success: function(resposeJsonObject){

    }});

在控制器中
@RequestMapping(value = "/saveCustomer", method = RequestMethod.POST, consumes = "application/json")
    public @ResponseBody Status saveCustomer(@RequestBody String jsonString){
    //check whether u r receiving some data over here
    System.out.println("received :" + jsonString);
        try {
            customerService.saveCustomer(customer);
            return new Status(code, message);
        } catch (Exception e) {
            return new Status(0, e.toString());
        }
    }

10-06 13:40
查看更多