简体   繁体   English

使用Grails和JavaScript执行Ajax时出错

[英]Error when doing ajax with grails and javascript

I have this jquery function on the client side... 我在客户端有这个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'
                   });
            });

And this Grails code in the server side 而此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)
 }
 }

But when the button #add-car is pressed it returns nothing... What Am I doing wrong? 但是,当按下#add-car按钮时,它什么也没有返回……我在做什么错?

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. 如果未打印日志,则意味着您必须重新检查JavaScript。 Using Firebug may help in uncovering some tricky javascript bugs. 使用Firebug可能有助于发现一些棘手的JavaScript错误。


By the way, I think you should use "jQuery" instead of "$" sign in your javascript. 顺便说一句,我认为您应该在JavaScript中使用“ jQuery”而不是“ $”符号。 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?" 但是您最近的网址映射似乎是"/cars/$id?"
which im assuming requires an ID but from your javascript code you are not sending back any variable named Id 我假设需要一个ID,但是从您的JavaScript代码中,您没有发回任何名为Id变量

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM