简体   繁体   English

Ajax Bad Request 400 Rails

[英]Ajax Bad Request 400 Rails

I'm getting bad request error 400 using Ajax on Rails. 我在Rails上使用Ajax收到错误的请求错误400。 When i submit my form I have a string to send as parameter from Jquery and i want to retrieve it from params[:assignee] so i can extract the string and save it through my controller. 当我提交我的表单时,我有一个字符串作为参数从Jquery发送,我想从params [:assignee]检索它,所以我可以提取字符串并通过我的控制器保存。 My controller: 我的控制器:

    def create
    @task = Task.new(task_params)
    @task.user = current_user
    username = params.permit[:assignee]
    @task.assignee = username

    #set_category
    respond_to do |format|
      if @task.save
        format.html { redirect_to tasks_url, notice: 'Task was successfully created. '+task_params.inspect}

        #format.html { redirect_to @task, notice: 'Task was successfully created.' }
        format.json { render :show, status: :created, location: @task }
      else
        format.html { render :new }
        format.json { render json: @task.errors, status: :unprocessable_entity }
      end
    end
  end

def task_params
  params.require(:task).permit(:owner, :value, :completed, :category, :date, :assignee)

end

And this is my JS: 这是我的JS:

 $( "#new_task" ).submit(function() {
    alert("form: "+assignee);
  //event.preventDefault();
 $.ajax({
   url: "/tasks",
   type: "POST",
   data: {assignee},
   dataType: "json",
   success: function(data) {
       alert('successfully');
     },
    error: function(xhr, textStatus, error) {
     alert(xhr.statusText+""+textStatus+""+error);
  }
   });
});

assignee is an username selected in a jquery auto-complete form: assignee是在jquery自动完成表单中选择的用户名:

select: function(event, ui) {
    var terms = split(this.value);
    // remove the current input
    terms.pop();
    // add the selected item
    terms.push(ui.item.value);
    // add placeholder to get the comma-and-space at the end
    terms.push("");
    this.value = terms.join("");
    assignee=this.value;
    $('input[name=commit]').prop("disabled",false);

    return false;
}

My root is "task/" where you can see saved tasks and a form to create a new one. 我的根是“任务/”,您可以在其中查看已保存的任务和创建新任务的表单。 I searched a lot on the net and I tried them all. 我在网上搜索了很多,我试了一下。 How can I do? 我能怎么做? Thanks so much 非常感谢

400 Bad Request - The server cannot or will not process the request due to an apparent client error (eg, malformed request syntax , too large size, invalid request message framing, or deceptive request routing). 400错误请求 - 由于明显的客户端错误(例如, 格式错误的请求语法 ,太大的大小,无效的请求消息框架或欺骗性请求路由),服务器无法或不会处理请求。

wiki 维基

Change the ajax code to: ajax代码更改为:

$.ajax({
   url: "/tasks",
   type: "POST",
   dataType: "json",
   headers: {
      'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'), // Optional
      'Content-Type': 'application/json'
   },
   data: JSON.stringify({ assignee: assignee }),
   success: function(data) {
       alert('successfully');
   },
   error: function(xhr, textStatus, error) {
     alert(xhr.statusText+""+textStatus+""+error);
   }
});

{assignee} that's a not valid JSON object it should be {assignee: assignee} Also you should add a valid headers, The 'Content-Type' and ( X-CSRF-TOKEN optional) {assignee}这是一个无效的JSON对象应该是{assignee: assignee}你还应该添加一个有效的标题, 'Content-Type'和( X-CSRF-TOKEN可选)

Solved! 解决了!

    $( "#new_task" ).submit(function(event) {
    alert("form: "+assignee);
    var value = $('#new_task').find('input[name="task[value]"]').val();
event.preventDefault();
 $.ajax({
   url: "/tasks",
   type: "post",
   contentType: "application/json",

   data: JSON.stringify({ assignee: assignee, value: value }),
   success: function(data) {
       alert('successfully');
   },
   error: function(xhr, textStatus, error) {
     alert(xhr.statusText+" "+textStatus+" "+error);
   }
});

});

event.preventDefault(); --> without this, the form is submitted twice. - >没有这个,表格提交两次。

var value = $('#new_task').find('input[name="task[value]"]').val(); --> without this, i could lose my form value because of "post tasks" that reminds to task#create - >没有这个,我可能会因为提醒任务#create的“post tasks”而失去我的表单值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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