无法通过json对象通过ajax发送表单数据

时间:2014-11-16 17:27:56

标签: ajax json jersey

我正在尝试通过jersey api中的ajax发送json数据。但是我无法发送数据。这是我的代码:

javascript代码

var jsonObj = createDataObj();

    $.ajax({    
                type : "POST",
                url : "/api/orders/addOrder",
                data : jsonObj ,
                contentType: "application/json",
                 error: function (xhr, ajaxOptions, thrownError) {
                        alert(thrownError);
                      }
                })
                  .done(function( response ) {
                     if(response.isSaved){
                         alert("Your order has been placed successfully & order id is "+response.orderId);
                     }
                     else{
                         alert("Soming went wrong. Please try again.");
                     }
                  });   


//creating json object    

function createDataObj(){
        var dataObj = "" + "{" + '"customerId":'+ $('#custId').val()+','+ '"companyName":'+'"'+$("#companyKey").val()+'",'
            + '"street" : '+'"'+$("#streetKey").val()+'",'+'"postalCode" : '+'"'+$("#postalCodeKey").val()+'",'+
            '"city":'+'"'+$("#cityKey").val()+'",' + '"country":'+'"'+$("#countryKey").val()+'",' 
            + '"productId":"'+  $("#product").val())+'",' +  '"quantity":'+ $('#quantity').val() + "} ";
        return dataObj;

    }

和球衣类

package elisa.devtest.endtoend;

import java.util.Collection;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import elisa.devtest.endtoend.dao.OrderDao;
import elisa.devtest.endtoend.model.Customer;
import elisa.devtest.endtoend.model.DataDto;
import elisa.devtest.endtoend.model.Order;

@Path("/orders")
public class OrderResource {

    private static final Logger log = Logger.getLogger(OrderResource.class
            .getName());

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Collection<Order> getOrders() {
        return new OrderDao().findOrders();
    }

    /**
     * @param name
     * @param company
     * @param Country
     * @param cityKey
     * @param postalCodeKey
     * @param Street
     * @param product
     * @param quant
     * @return Method addByPassingValue method used to fetch the data from form
     *         and sent it DAO for insertion in database. This Method is called
     *         when submit button is clicked on form
     */
    @POST
    @Path("/addOrder")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public String addByPassingValue(DataDto obj) {
        StringBuilder response = new StringBuilder();
        try{

        log.log(Level.SEVERE, "OrderResource", "Processing records");

        response.append("success");

        Customer cust = new Customer(2, "test", "test",
                "test", "test", "test");

    //  Customer cust = new Customer(Integer.parseInt(custId), company, Street,
        //      postalCodeKey, cityKey, Country);
    //  new OrderService().addOrder(obj.getCustomer(), "f3DFS234#212dfS", 3);

        return response.toString();
        }   catch(IllegalArgumentException e){
            e.printStackTrace();
            return response.append("{\"isSaved\":").append(false).append("}").toString();

        }
        catch(Exception e){
            e.printStackTrace();
            return response.append("{\"isSaved\":").append(false).append("}").toString();
        }


    }


}

where DataDto has setter and getter method

problem is I am not able to call method through ajax call

please help 
thanks in advance

1 个答案:

答案 0 :(得分:0)

希望这会有所帮助:

您的javascript可以像这样修改:

var jsonObj = createDataObj();

$.ajax({
    type: "POST",
    url: "http://localhost:8080/YourProjectName/api/orders/addOrder",
    data: jsonObj,
    contentType: 'application/json',
    success: function(jsonResp) {
        alert(jsonResp);
    },
    error: function(xhr) {
        alert(JSON.stringify(xhr));
    }
});

function createDataObj() {
    var dataObj = "" + "{" + '"customerId":' + $('#custId').val() + ',' + '"companyName":' + '"' + $("#companyKey").val() + '",'
            + '"street" : ' + '"' + $("#streetKey").val() + '",' + '"postalCode" : ' + '"' + $("#postalCodeKey").val() + '",' +
            '"city":' + '"' + $("#cityKey").val() + '",' + '"country":' + '"' + $("#countryKey").val() + '",'
            + '"productId":"' + $("#product").val() + '",' + '"quantity":' + $('#quantity').val() + "} ";
    return dataObj;
}

您的Java方法应如下所示:

@POST
@Path("/addOrder")
@Consumes(MediaType.APPLICATION_JSON)
public Response addByPassingValue(DataDto obj) {
    log.log(Level.SEVERE, "OrderResource", "Processing records");
    Customer cust = new Customer(2, "test", "test",
        "test", "test", "test");
    return Response.status(200).entity("Success").build();
}