如何使用 Ajax 获取在输入字段中输入的内容?

How do I fetch the contents entered in the Input field using Ajax?

我在表单中有一个输入字段,用户可以通过单击按钮更新他们的姓名。输入字段中的此更改应由 Ajax 捕获并更新它。

Html -

<p id="name"><%= @current_user.name %></p>

<button type="button" id="namebtn">&#xE254;</i> </button>

咖啡脚本 -

$('form').on 'focusout', ->
    $elem = $(this)
    if !$elem.find(':focus').length
            $.ajax({
                type: "POST",
                url: "http://localhost:3000/profile/name_change",
                data: "{
                    'name': '"+$('#name').val()+"'}",
            })
        return

如何从输入字段捕获更改的输入?

你说你有一个 'input field',但 #name 显然是一个 p 元素。在这种情况下,您需要使用 text() 来获取它的值。

另请注意,您在检查 :focus 元素时在表单上使用 focusout 是相当奇怪的。您可以改用标准 click 处理程序:

$('#namebtn').on 'click', ->
  $.ajax({
    type: "POST",
    url: "http://localhost:3000/profile/name_change",
    data: { name: $('#name').text() }
  })
  return