これらの投稿がたくさんあることは知っていますが、RESTとJQueryの両方に慣れていないため、これを実際に機能させることができませんでした:
私は Java 5 で REST-WS を使用しています。それを呼び出して、それをテストするための firefox プラグインである「Poster」で結果を返すことができます。以下の URL を呼び出すと、以下に示すリソース クラスでメソッド「getCustomer」を呼び出して、マップ内の順序 '0' の従業員を取得する必要があります。
結果を取得できず、jQuery を使用して「unknown」というエラーが表示されますが、次のように本文を持つ HTML ページから REST を呼び出すと、JSON が返されます。
<body>
jQuery to REST <br><br>
<a href="http://jquery.com/">jQuery</a>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function (){
$.ajax({
type: "GET",
url: "http://localhost:8081/RestDemo/services/customers/0",
dataType: "json",
success: function (data) {
alert(data.name);
},
error: function(e){
alert("Error: " + e);
}
});
});
});
</script>
<br>
<br>
<button>Return Customer</button>
</body>
これは私の Resource クラスです:
package com.myeclipseide.ws;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import com.sun.jersey.spi.resource.Singleton;
@Produces("application/xml")
@Path("customers")
@Singleton
@XmlRootElement(name = "customers")
public class CustomerResource {
private TreeMap<Integer, Customer> customerMap = new TreeMap<Integer, Customer>();
public CustomerResource() {
// hardcode a single customer into the database for demonstration
// purposes
Customer customer = new Customer();
customer.setName("Harold Abernathy");
customer.setAddress("Sheffield, UK");
addCustomer(customer);
}
@GET
@XmlElement(name = "customer")
public List<Customer> getCustomers() {
List<Customer> customers = new ArrayList<Customer>();
customers.addAll(customerMap.values());
return customers;
}
@GET
@Path("/{id}")
@Produces("application/json")
public String getCustomer(@PathParam("id") int cId) {
return "{\"name\": \"unknown\", \"address\": -1}"; //customerMap.get(cId);
}
@POST
@Path("add")
@Produces("text/html")
@Consumes("application/xml")
public String addCustomer(Customer customer) {
int id = customerMap.size();
customer.setId(id);
customerMap.put(id, customer);
return "Customer " + customer.getName() + " added with Id " + id;
}
}
誰の助けにも感謝します、
ありがとう!