$ .post(url,function(data,status){alert(data)}); alert()无效

时间:2014-09-28 17:27:03

标签: javascript jquery ruby-on-rails post httpresponse

我有一个Rails应用程序,它与其他rails应用程序进行通信以进行数据插入。我使用jQuery $.post方法进行数据插入。对于插入,我的其他Rails应用显示200 OK。但是在post方法的功能警报中并没有显示任何内容。

jQuery代码:

$.post("http://localhost:3000/persons.json",
    { 
        person: 
        { 
            id: $("#id").val(), 
            name: $("#name").val(), 
        } 
    },function(data, status){
        alert("Hello World!!");
        alert("Data: " + data + "\nStatus: " + status);
    });

其他Rails App中的控制器代码:

p = Person.new(a_params)
if p.save
    notice = "Person data entered successfully"
    render json: notice, status: 200
end

我哪里错了?

1 个答案:

答案 0 :(得分:1)

您没有将正确的JSON对象作为响应返回,因此jQuery将响应解释为error而不是success

您可能想尝试一下:

p = Person.new(a_params)
if p.save
  notice = "Person data entered successfully"
  render json: {notice: notice, status: 200} # This ruby Hash is returned as a JSON object
end

然后在您的jQuery代码中,您可以访问data['notice']data['status']