Phonegap Ajax Post to Rails 3.2.2获取MultiJson :: DecodeError(756:意外令牌)

时间:2012-04-23 03:59:54

标签: javascript ruby-on-rails ajax cordova

我试图从phonegap到rails 3.2.2脚手架做一个简单的帖子。我有一个简单的脚手架,由一个控制器组成=>图像和一个字段=> t.string:名称

class ImagesController < ApplicationController
  # GET /images
  # GET /images.json
  def index
    @images = Image.all

    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @images }
    end
  end

  # GET /images/1
  # GET /images/1.json 
  def show
    @image = Image.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.json { render json: @image }
    end
  end

  # GET /images/new
  # GET /images/new.json
  def new
    @image = Image.new

    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @image }
    end
  end

  # GET /images/1/edit
  def edit
    @image = Image.find(params[:id])
  end

  # POST /images
  # POST /images.json
  def create
    @image = Image.new(params[:image])

    respond_to do |format|
      if @image.save
        format.html { redirect_to @image, notice: 'Image was successfully created.' }
        format.json { render json: @image, status: :created, location: @image }
      else
        format.html { render action: "new" }
        format.json { render json: @image.errors, status: :unprocessable_entity }
      end
    end
  end

  # PUT /images/1
  # PUT /images/1.json
  def update
    @image = Image.find(params[:id])

    respond_to do |format|
      if @image.update_attributes(params[:image])
        format.html { redirect_to @image, notice: 'Image was successfully updated.' }
        format.json { head :no_content }
      else
        format.html { render action: "edit" }
        format.json { render json: @image.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /images/1
  # DELETE /images/1.json
  def destroy
    @image = Image.find(params[:id])
    @image.destroy

    respond_to do |format|
      format.html { redirect_to images_url }
      format.json { head :no_content }
    end
  end
end

来自phonegap应用的index.html文件是:

<!DOCTYPE HTML>
<html>
<head>
<title>PhoneGap</title>
<script type="text/javascript" charset="utf-8" src="cordova-1.6.1.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script type="text/javascript" charset="utf-8">

  function appReady(){

     var ajax = new XMLHttpRequest();
 var data = '{ image: { name: "noway" } }';
     ajax.open("POST","http://<server>/images.json",true);
     ajax.setRequestHeader("Content-type", "application/json")
     ajax.send(data);

     ajax.onreadystatechange=function(){
          if(ajax.readyState==4 && (ajax.status==200)){
               document.getElementById('main').innerHTML = ajax.responseText;
          }
     }
}


  document.addEventListener("deviceready", appReady, false);

    </script>
</head>
<body>

<h1>Hello World</h1>
<div id="main">
</div>
</body>
</html>

webrick控制台产生以下内容:

Started POST "/images.json" for 10.0.1.14 at 2012-04-22 22:32:58 -0500
Error occurred while parsing request parameters.
Contents:

MultiJson::DecodeError (756: unexpected token at '{ image: { name: "noway" } }'):
  json (1.6.6) lib/json/common.rb:148:in `parse'

我认为这与我格式化json对象的方式有关,因为当我改变时:

var data = '{ image: { name: "noway" } }';

为:

var data = " ";

我明白了:

Started POST "/images.json" for 10.0.1.14 at 2012-04-22 22:57:03 -0500
Processing by ImagesController#create as JSON
  Parameters: {"image"=>{}}
WARNING: Can't verify CSRF token authenticity
   (0.1ms)  begin transaction
  SQL (24.1ms)  INSERT INTO "images" ("created_at", "name", "updated_at") VALUES (?, ?,  ?)  [["created_at", Mon, 23 Apr 2012 03:57:03 UTC +00:00], ["name", nil], ["updated_at",   Mon, 23 Apr 2012 03:57:03 UTC +00:00]]
   (46.0ms)  commit transaction
Completed 201 Created in 76ms (Views: 1.9ms | ActiveRecord: 70.2ms)

我是不是错过了形成json数据?

1 个答案:

答案 0 :(得分:2)

我能够POST更改线路:

var data = '{ image: { name: "noway" } }';

为:

var data = JSON.stringify({ image: { name: "noway" } });

使用JSON stringify方法在webrick中产生以下结果:

Started POST "/images.json" for 192.168.1.139 at 2012-04-23 17:54:58 -0500
Processing by ImagesController#create as JSON
  Parameters: {"image"=>{"name"=>"noway"}}
WARNING: Can't verify CSRF token authenticity
   (0.1ms)  begin transaction
  SQL (1.1ms)  INSERT INTO "images" ("created_at", "name", "updated_at") VALUES (?, ?, ?)  [["created_at", Mon, 23 Apr 2012 22:54:58 UTC +00:00], ["name", "noway"], ["updated_at",   Mon, 23 Apr 2012 22:54:58 UTC +00:00]]
   (45.8ms)  commit transaction
Completed 201 Created in 51ms (Views: 1.4ms | ActiveRecord: 47.0ms)