簡體   English   中英

$ .post(URL,function(data,status){alert(data)}); alert()不起作用

[英]$.post(url, function(data,status) {alert(data)}); alert() not working

我有一個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應用中的控制器代碼:

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

我要去哪里錯了?

您沒有返回適當的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']

暫無
暫無

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

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