简体   繁体   中英

jQuery AJAX POST on Rails migraine

I'm running a JS game off file:// and trying to make a post request to a localhost Rails server to add a high score entry.

JS:

  highScoresEntryView.keyHandlers = function() {
    var that = this;
    this.parent.keydown(function(event) {
      event.preventDefault();
      event.stopPropagation();
      if(event.which == 27) {
        //...
      } else if (event.which == 13) {
        if(that.entryString !== "") {
          that.scoreObject.score.player = that.entryString;
          that.submitScore(that.scoreObject);
        } else { 
          AsteroidsUI.initializeMainMenu();
        }
      }
    });
  };

  highScoresEntryView.submitScore = function() {
    var that = this;
    $.ajax({
      type: "POST",
      url: AsteroidsUI.highScoresHost, //http://localhost:3000/scores/
      data: that.scoreObject,
      crossDomain: true,
      dataType: "json",
      success: function(a, b, c) {
        console.log(a);
        console.log(b);
        console.log(c);
        alert("Congrobulations! Score sent.");
        AsteroidsUI.initializeMainMenu();
      },
      error: function(a, b, c) {
        console.log(a);
        console.log(b);
        console.log(c);
        alert("Could not send score :(");
        AsteroidsUI.initializeHighScoresEntry(that.scoreObject);
      }
    });
  };

Controller:

  def create
    @score = Score.new(params[:score])
    if @score.save
      render :json => @score, :status => 201
    else
      render :json => { :errors => @score.errors.full_messages }, :status => 422
    end
  end

I get a response back with status 201 and the database makes an entry, but when I check the response in firebug, it appears blank and the error handler for the ajax request fires rather than the success handler. I've looked through about a dozen similar questions and none of the solutions have worked for me so far - I've tried changing dataType between text, html, and json, same outcome.

This was a CORS problem. I solved it by adding the following code similar to this tutorial to my Rails controller:

  def set_headers
    headers['Access-Control-Allow-Origin'] = '*'
    headers['Access-Control-Expose-Headers'] = 'ETag'
    headers['Access-Control-Allow-Methods'] = 'GET, POST'
    headers['Access-Control-Allow-Headers'] = '*,x-requested-with,Content-Type,If-Modified-Since,If-None-Match'
    headers['Access-Control-Max-Age'] = '86400'
  end

I'm not really sure why this worked to allow the success callback. Does AJAX require these headers in the response to engage the success callback?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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