如何在 jquery ajax 中发送 json 格式的数据以实现 restfull web 服务

问题描述 投票:0回答:4

我在 jquery ajax 中发送 json 格式的数据用于 restful web 服务,但它没有发送。我是网络技术的新手,所以请帮助我。我使用以下链接编写用于发送 JSON 数据的脚本 如何通过ajax将JSON数据传递给restful web服务以及如何获取JSON数据?

我的javascript代码是

<script type="text/javascript">
 $(document).ready(function(){           
     $('#btnBooking').click(function(){  
             var serviceCategory=document.getElementById("services").value;
             var availDate=document.getElementById("scheduledDate").value;
             var custName=document.getElementById("userName").value;     
             var custMobile=document.getElementById("userContactNumber").value;  
             var custEmail=document.getElementById("addressemailId").value;
             var custAddress=document.getElementById("address1").value;
             var JSONObject= {"serviceCategory":serviceCategory, "availDate":availDate, "custName":custName, "custMobile":custMobile, "custEmail":custEmail, "custAddress":custAddress};
             var jsonData = JSON.stringify( JSONObject );
             $.ajax({
                 url: "http://localhost:8080/HomeServiceProvider/rest/booking/saveBookingDetails",
                 type: "POST",
                 dataType: "json",                  
                 data: jsonData,
                 contentType: "application/json",
                 success: function(response){
                    alert(JSON.stringify(response));
                 },
                 error: function(err){
                    alert(JSON.stringify(err));
                 }
            });     
     });  
}); 


</script>

我的Html代码是

<form class="form-horizontal" id="scheduleLaterForm" name="scheduleLaterForm" action="#" method="post">
    <div class="col-lg-8">
        <div class="alert alert-danger alert-dismissable" style="display: none;" id="errorMessageDiv">Error
                Message Goes Here</div>                                     
        <div class="form-group">
                    <label class="col-lg-3 control-label">Name:<font style="color: red;">*</font></label>
                    <div class="col-lg-9">
                        <input class="form-control" id="userName" name="userName" placeholder="Full Name" value="" type="text">
                    </div>
        </div>                          

        <div class="form-group">
            <label class="col-lg-3 control-label">Services:</label>
            <div class="col-lg-9">
                <select class="form-control" id="services" name="subService">
                    <option>Select Service</option> 
                    <option value="1">Carpenter</option>    
                    <option value="2">Mobile SIM services</option>  
                </select>
            </div>
        </div>                                  

        <div class="form-group">
            <label for="schedule-tme" class="col-lg-3 control-label">Schedule Date:<font style="color: red;">*</font></label>
            <div class="col-lg-9">
                <div class="input-group date form_datetime" data-date="dd-M-yyyy">
                    <input placeholder="Choose Date" class="form-control" value="" onchange="timeValidate()" id="scheduledDate" name="scheduledDate" readonly="readonly" type="text"> <span class="input-group-addon"> <span class="glyphicon glyphicon-th calender-click"></span></span>
                </div>
            </div>
        </div>

        <div class="form-group">
            <label class="col-lg-3 control-label">Address:<font style="color: red;">*</font></label>
            <div class="col-lg-9">
                <input class="form-control" name="address1" id="address1" placeholder="Full address" value="" type="text">
            </div>
        </div>



        <div class="form-group">
            <label class="col-lg-3 control-label">City:</label>
            <div class="col-lg-9">
                <input class="form-control" id="" value="Bangalore" name="" placeholder="City Name" readonly="readonly" type="text">
            </div>
        </div>

        <div class="form-group">
            <label class="col-lg-3 control-label">Mobile:<font style="color: red;">*</font></label>
            <div class="col-lg-9">
                <input class="form-control" id="userContactNumber" name="userContactNumber" placeholder="Mobile Number" onkeypress="enableKeys(event);" maxlength="10" type="text">
            </div>
        </div>

        <div class="form-group">
                <label class="col-lg-3 control-label">Email:<font style="color: red;">*</font></label>
                <div class="col-lg-9">                                      
                <input class="form-control" name="addressemailId" id="addressemailId" placeholder="[email protected]" value="" type="text">                                       

                </div>
        </div>

        <div class="form-group marg-bot-45">
            <label class="col-lg-3 control-label"></label>
            <div class="col-lg-9">
                <a href="index.html" class="btn btn-info"  id="btnBooking">Confirm Booking&nbsp;<span class="glyphicon glyphicon-ok"></span></a>
            </div>
        </div>
    </div>  
</form> 

预订.java

import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

import org.codehaus.jackson.annotate.JsonIgnoreProperties;

import com.fasterxml.jackson.annotation.JsonIgnore;

/**
 * Booking generated by hbm2java
 */
@Entity
@Table(name = "booking", catalog = "service4homes")
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class Booking implements java.io.Serializable {

    private Integer BId;
    private ServiceProviderStatus serviceProviderStatus;
    private ServiceCategory serviceCategory;
    private Date availDate;
    private String custName;
    private String custMobile;
    private String custEmail;
    private String custAddress;
    private Set<Allocation> allocations = new HashSet<Allocation>(0);
    private Set<SuperAdmin> superAdmins = new HashSet<SuperAdmin>(0);

    public Booking() {
    }

    public Booking(ServiceProviderStatus serviceProviderStatus,
            Customer customer, ServiceCategory serviceCategory, Date availDate,
            String custEmail) {
        this.serviceProviderStatus = serviceProviderStatus;
        this.serviceCategory = serviceCategory;
        this.availDate = availDate;
        this.custEmail = custEmail;
    }

    public Booking(ServiceProviderStatus serviceProviderStatus,
            Customer customer, ServiceCategory serviceCategory, Date availDate,
            String custName, String custMobile, String custEmail,
            String custAddress, Set<Allocation> allocations,
            Set<SuperAdmin> superAdmins) {
        this.serviceProviderStatus = serviceProviderStatus;
        this.serviceCategory = serviceCategory;
        this.availDate = availDate;
        this.custName = custName;
        this.custMobile = custMobile;
        this.custEmail = custEmail;
        this.custAddress = custAddress;
        this.allocations = allocations;
        this.superAdmins = superAdmins;
    }

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

    public void setBId(Integer BId) {
        this.BId = BId;
    }

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "sps_id", nullable = false)
    @JsonIgnore
    public ServiceProviderStatus getServiceProviderStatus() {
        return this.serviceProviderStatus;
    }

    public void setServiceProviderStatus(
            ServiceProviderStatus serviceProviderStatus) {
        this.serviceProviderStatus = serviceProviderStatus;
    }

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "sc_id", nullable = false)
    @JsonIgnore
    public ServiceCategory getServiceCategory() {
        return this.serviceCategory;
    }

    public void setServiceCategory(ServiceCategory serviceCategory) {
        this.serviceCategory = serviceCategory;
    }

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "avail_date", nullable = false, length = 19)
    public Date getAvailDate() {
        return this.availDate;
    }

    public void setAvailDate(Date availDate) {
        this.availDate = availDate;
    }

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

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

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

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

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

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

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

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

    @OneToMany(fetch = FetchType.EAGER, mappedBy = "booking")
    public Set<Allocation> getAllocations() {
        return this.allocations;
    }

    public void setAllocations(Set<Allocation> allocations) {
        this.allocations = allocations;
    }

    @OneToMany(fetch = FetchType.EAGER, mappedBy = "booking")
    @JsonIgnore
    public Set<SuperAdmin> getSuperAdmins() {
        return this.superAdmins;
    }

    public void setSuperAdmins(Set<SuperAdmin> superAdmins) {
        this.superAdmins = superAdmins;
    }

}
javascript jquery ajax json restful-url
4个回答
0
投票

我认为您还必须将

contentType
添加到
ajax
请求调用中,因为您正在尝试将
json
格式的数据发送到服务器,如下所示。

var request = $.ajax({
                 url: "http://localhost:8080/HomeServiceProvider/rest/booking/saveBookingDetails",
                 type: "POST",
                 data: jsonData,
                 contentType: "application/json",
                 dataType: "json"
            });   

dataType
: 数据格式,你期待的形式服务器

contentType
: 数据格式,你发送到服务器


0
投票

你确定它不起作用吗?我复制了与您相同的代码并尝试在我的域上执行并且它很好。这是代码,我用一些硬编码的数字替换了变量。

var jsonData = JSON.stringify({"serviceCategory": 4, "availDate":2, "custName":4, "custMobile":4, "custEmail":4, "custAddress":4});
$.ajax({
             url: "http://cloudpanel.abstractdns.com",
             type: "POST",
             dataType: "json",                  
             data: jsonData,
             contentType: "application/json",
             success: function(response){
                alert(JSON.stringify(response));
             },
             error: function(err){
                alert(JSON.stringify(err));
             }
        });  

这是 firefox 控制台的屏幕截图,显示

JSON
数据已正确发送。

enter image description here

上面的截图清楚地表明它以指定的格式发送了正确的数据。如果它不起作用,可以粘贴来自 firebug 的屏幕截图,这样我们就可以了解它是否真的不起作用,我这么说是因为你已经告诉过你是网络技术的新手。如果你不知道,你可以在 mozilla 和 chrome 上安装 firebug 并自己进行检查,这将使你深入了解任何错误。

关于您的评论,您已声明您收到有关 CORS 的错误。所以这可以通过将

dataType: json
替换为
dataType: "jsonp"
来解决。如果具有 ajax 的应用程序和 ajax 发送请求的应用程序位于不同的服务器上,那应该可以解决您的问题。

希望有帮助


0
投票

你混淆了 JSON.parse() 和 JSON.stringify()

JSON.parse(): JSON.parse() 方法将字符串解析为 JSON,可选择转换解析产生的值。

JSON.stringify(): JSON.stringify() 方法将 JavaScript 值转换为 JSON 字符串,如果指定了替换函数,则可选择替换值,或者如果指定了替换数组,则可选择仅包含指定的属性。

所以在你的代码中,你必须将 JSON.parse 更改为 JSON.stringify


0
投票

你必须发送一个字符串,它是 Json 数据。所以用 JSON.stringify 转换你的 javascript 对象“JSONObject”

var JSONObject= ...;
var jsonData = JSON.stringify( JSONObject );

在这里你可以找到一个例子,如果你更频繁地需要这个功能,你可以如何扩展 jquery 来拥有一个 postJSON 函数。

© www.soinside.com 2019 - 2024. All rights reserved.