I have this jquery function on the client side...
$('#add-car').on('click', function() {
$.ajax({
type: 'POST',
url: 'cars/',
data: {brand: 'brand', model: 'model', price: 100,
registryYear:1999},
success: function(data) { console.log(data)},
dataType: 'json'
});
});
And this Grails code in the server side
class UrlMappings {
static mappings = {
"/cars/$id?"(controller: "cars") {
action = [GET:"list", POST:"save", DELETE:"delete", PUT:"edit"]
}
"/$controller/$action?/$id?"{
constraints {
// apply constraints here
}
}
"/"(view:"/index")
"500"(view:'/error')
}
}
import grails.converters.JSON
class CarsController {
def index() {
render ( Car.findAll() as JSON )
}
def save() {
def json = request.JSON
def car = new Car(json)
car.save()
render (json)
}
def delete() {
def car = Car.findById(params.id)
car?.delete()
render (car as JSON)
}
def edit() {
def car = Car.findById(params.id)
bindData(car, request.JSON)
render (car.save() as JSON)
}
}
But when the button #add-car is pressed it returns nothing... What Am I doing wrong?
This is about debugging method.
Please check if the request comes to your server or not. You can do that by adding some logs "Running here" into your requested action at the controller.
If the "Running here" get printed, the request was sent and you must find out how the server doesn't return the expected result.
If the log doesn't get printed, it means you must re-check your javascript. Using Firebug may help in uncovering some tricky javascript bugs.
By the way, I think you should use "jQuery" instead of "$" sign in your javascript. That is for avoiding conflicts with other libraries, such as:
jQuery('#add-car').click(function() {
....
});
well i dont code in grails
but your closest url mapping appears to be this "/cars/$id?"
which im assuming requires an ID but from your javascript code you are not sending back any variable named Id
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.