java - 如何使用 JQuery + Ajax 发送将由 RestFulServices 使用的 JSON 对象数据?

标签 java jquery mysql json hibernate

我必须使用 JQuery+Ajax 发送将由 RestFulWebServices 使用的 JSON 对象数据。在后端,我使用的是 hibernate(ver 4)+Maven(ver 3)+spring(ver 4)、MySql 数据库和 ApacheTopcat 服务器(ver 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

我的客户休息 Controller 是 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 数据 enter image description here

点击按钮后 enter image description here enter image description here

最佳答案

$.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){

    }});

在 Controller 中,

@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());
        }
    }

关于java - 如何使用 JQuery + Ajax 发送将由 RestFulServices 使用的 JSON 对象数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28047585/

相关文章:

php - 将 php while 数组结果分配给可变数量的变量

php - 内连接表时执行删除

java - 构建一个只能执行的JAR文件?

javascript - SAPUI5通过点击在新创建的控件(面板)中绘制谷歌图表

javascript - 使用 jQuery 选择不包含 <span class ="foo"> 的 <p> 元素(选择性切换的最终目标)

javascript - 可以在灯箱中将整个未修改的网站显示在另一个网站之上吗?

php - Laravel:查询根据我在 URL 中传递的 ID 返回数据

java - 一对一映射的mappyBy属性创建异常: cannot simultaneously fetch multiple bags

java - java读取jar内的文件

java - Android 单例线程安全