gpt4 book ai didi

javascript - 来自 jQuery 的 Rails : ensure that $. post 在 Controller 中作为 format.json 接收

转载 作者:行者123 更新时间:2023-11-30 13:21:30 24 4
gpt4 key购买 nike

我有一个 jQuery 脚本试图像这样发布数据:

$.post({
$('div#location_select').data('cities-path'),
{ location_string: $('input#city_name').val() },
});

这可行,但由于某种原因,服务器将其作为 HTML 请求而不是 JS 请求接收。是什么赋予了?这是我的 Controller 中的响应 block :

if @city.save
respond_to do |format|
format.html { redirect_to @city }
format.json { render :json => @city, :status => :ok }
end
else
respond_to do |format|
format.html { render :new }
format.json { render :json => { :error => "Incorrect location format, please input a city and state or country, separated by a comma." }, :status => :unprocessable_entity }
end
end

如何确保 Ajax 请求到达 Controller 并由 format.js 响应程序处理?


更新:当我从 $.post 更改为 $.ajax 并专门定义了数据类型时:

$.ajax({
type: 'POST',
url: $('div#location_select').data('cities-path'),
data: { location_string: $('input#city_name').val() },
dataType: 'json'
});

最佳答案

您是否通过 routes.rb 中的路由传递格式?

"controller/action/(.:format)"

关于javascript - 来自 jQuery 的 Rails : ensure that $. post 在 Controller 中作为 format.json 接收,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10131153/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com