为什么我的 AJAX 获取请求并不总是 returns 正确的值、RoR、CoffeeScript

Why my AJAX get request not always returns correct value, RoR, CoffeeScript

我的 CoffeeScript 文件如下所示:

updateDot = (iDraggingID, newX, newY) ->
  $.ajax "/dots/#{iDraggingID}",
    type:'PUT'
    dataType:'json'
    data: {dot: {position_x: "#{newX}", position_y: "#{newY}"}}

refreshDot = (id) ->
  $.ajax
    url: "/dots/#{id}"
    type: "GET"
    dataType: 'json'
    success: (data) ->
    moveDot data['position_x'], data['position_y'], "dot#{id}"

handleDragStop = (event, ui) ->
  newX = parseInt( ui.offset.left );
  newY = parseInt( ui.offset.top );
  sDraggingID = $(this).attr 'id'
  iDraggingID = sDraggingID.match(/\d+/)[0]
  updateDot iDraggingID, newX, newY
  refreshDot(iDraggingID)

moveDot = (x, y, id) ->
  document.getElementById(id).style.left = "#{x}px";
  document.getElementById(id).style.top = "#{y}px";

moveDots = (x) ->
  moveDot(i['position_x'], i['position_y'], "dot#{i['id']}") for i in x

jQuery -> # starts all of this
  moveDots gon.dots #basically returns JSON with all elements from database
  $('.dot').draggable
    containment: '#parent',
    cursor: 'move',
    stop: handleDragStop #when dragging an element is done trigger this

还有我的控制器:

class DotsController < ApplicationController

def index
  @dots = Dot.all
  respond_to do |format|
    format.html { render :nothing => true }
    format.json { render :json => @dots, :status => :ok }
  end
end

def show
  @dot = Dot.find(params[:id])

  respond_to do |format|
    format.html  { render :nothing => true }
    format.json  { render :json => @dot, :status => :ok }
  end
end

def create
  @dot = Dot.new(dot_params)
  @dot.save
end

def update
  @dot = Dot.find(params[:id])
  @dot.update_attributes(dot_edit_params)

  respond_to do |format|
    format.html  { render :nothing => true }
    format.json  { render :json => @dot, :status => :ok}
  end
end

def destroy
   @dot = Dot.(params[:id])
   @dot.destroy
end
private
  def dot_params
    params.require(:dot).permit(:name, :position_x, :position_y)
  end

  def dot_edit_params
    params.require(:dot).permit(:position_x, :position_y)
  end
end

为什么有时当我从 CoffeeScript 调用 refreshDot 时,我得到 position_x 和 position_y 的正确值……而有时我得到的是旧值???好像是70:30good:badreturns.

这是因为在 PUT 方法实际结束之前(以某种方式)调用了 GET 方法......还是什么?我很困惑

使用异步 (AJAX) 请求的性质意味着第二个可能先于第一个完成。如果有依赖,考虑使用回调。

像这样:

updateDot = (iDraggingID, newX, newY) ->
  $.ajax "/dots/#{iDraggingID}",
    type:'PUT'
    dataType:'json'
    data: {dot: {position_x: "#{newX}", position_y: "#{newY}"}}
    success: (data) ->
      moveDot data['position_x'], data['position_y'], "dot#{id}"

handleDragStop = (event, ui) ->
  newX = parseInt( ui.offset.left );
  newY = parseInt( ui.offset.top );
  sDraggingID = $(this).attr 'id'
  iDraggingID = sDraggingID.match(/\d+/)[0]
  updateDot iDraggingID, newX, newY