使用 grails 和 javascript 执行 ajax 时出错

Error when doing ajax with grails and javascript

本文关键字:ajax 出错 执行 javascript grails 使用      更新时间:2023-09-26

我在客户端有这个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'
                   });
            });

而这个圣杯代码在服务器端

    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 车的按钮时,它什么也没返回......我做错了什么?

这是关于调试方法的。

请检查请求是否到达您的服务器。您可以通过在控制器的请求操作中添加一些日志"在此处运行"来做到这一点。

如果打印了"运行此处",则请求已发送,您必须找出服务器如何不返回预期结果。

如果日志没有被打印出来,这意味着你必须重新检查你的javascript。使用Firebug可能有助于发现一些棘手的JavaScript错误。


顺便说一下,我认为你应该在你的javascript中使用"jQuery"而不是"$"符号。这是为了避免与其他库发生冲突,例如:

jQuery('#add-car').click(function() {
....
            });
好吧,

我不用grails
编码但您最近的 URL 映射似乎是这个"/cars/$id?"
IM 假设需要一个 ID但是从你的JavaScript代码中,你不会发回任何名为Id的变量