我在客户端有这个jquery函数......
$('#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'
});
});
这个Grails代码在服务器端
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)
}
}
但是当按下#add-car按钮时,它什么也没有返回......我做错了什么?
答案 0 :(得分:0)
这是关于调试方法。
请检查请求是否发送到您的服务器。您可以通过在控制器上添加一些“在此处运行”日志来执行此操作。
如果打印“正在运行”,请求已发送,您必须了解服务器如何不返回预期结果。
如果日志未打印,则表示您必须重新检查您的JavaScript。使用Firebug可能有助于发现一些棘手的javascript错误。
顺便说一句,我认为你应该在你的javascript中使用“jQuery”而不是“$”符号。这是为了避免与其他库发生冲突,例如:
jQuery('#add-car').click(function() {
....
});
答案 1 :(得分:0)
"/cars/$id?"
我假设需要一个ID
但是从您的javascript代码中,您不会发回任何名为Id
的变量