簡體   English   中英

使用Grails和JavaScript執行Ajax時出錯

[英]Error when doing ajax with grails and javascript

我在客戶端有這個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按鈕時,它什么也沒有返回……我在做什么錯?

這是關於調試方法。

請檢查請求是否到達您的服務器。 您可以通過在控制器上向請求的操作中添加一些“在此處運行”日志來實現。

如果打印了“在此運行”,則發送請求,並且您必須找出服務器如何不返回預期結果。

如果未打印日志,則意味着您必須重新檢查JavaScript。 使用Firebug可能有助於發現一些棘手的JavaScript錯誤。


順便說一句,我認為您應該在JavaScript中使用“ jQuery”而不是“ $”符號。 這是為了避免與其他庫發生沖突,例如:

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

好吧,我不寫代碼
但是您最近的網址映射似乎是"/cars/$id?"
我假設需要一個ID,但是從您的JavaScript代碼中,您沒有發回任何名為Id變量

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM