如何修改beforeSend事件中的ajax Post数据?
您好,我有一个使用 Rails 的 jQuery UJS 远程提交的表单。我绑定到 beforeSend 事件,以允许我修改提交到服务的数据。它不起作用。这是我在 beforeSend 中的内容:
settings.data = JSON.stringify({
'list_item[title]' : 'hi?? there'
})
这不起作用。在服务器日志中我看到:
Started POST "/lists/9/list_items" for 127.0.0.1 at 2011-10-24 14:04:36 -0700
Processing by ListItemsController#create as JSON
Parameters: {"{\"list_item"=>{"title"=>{"\":\"hi?? there\"}"=>nil}}, "list_id"=>"9"}
知道我做错了什么吗?我想使用表单中没有的添加字段来自定义 settings.data 。谢谢
Hello I have a form that submits remotely with the jQuery UJS for rails. I binded to the beforeSend event to allow me to modify the data submitting to the serve. It's not working. Here is what I have in the beforeSend:
settings.data = JSON.stringify({
'list_item[title]' : 'hi?? there'
})
This doesn't work. In the server logs I see this:
Started POST "/lists/9/list_items" for 127.0.0.1 at 2011-10-24 14:04:36 -0700
Processing by ListItemsController#create as JSON
Parameters: {"{\"list_item"=>{"title"=>{"\":\"hi?? there\"}"=>nil}}, "list_id"=>"9"}
Any idea what I'm doing wrong? I want to customize the settings.data with added fields that aren't in the form. Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您无需对任何内容进行字符串化即可将其放入
settings.data
中。数据
是:您正在做的是将这个字符串:
放入
data
中,但该字符串不是查询字符串,因此事情会变得混乱。您应该能够简单地将 JavaScript 对象分配给settings.data
:并让 jQuery 从那里对其进行排序。
基于证据而不是文档进行更新:
然而,进一步的调查表明这不起作用。如果我发送 GET 请求,我对
settings.data
所做的任何更改都会被忽略,但如果我发送 POST 请求,则会对settings.data
进行更改,但您必须使用查询字符串格式来获取任何有意义的内容:settings.data
的版本与 POST 请求相结合,让我得到这个:在服务器上,这看起来像您所追求的。如果您想保留一些原始参数,那么您必须手动解包并重新打包查询字符串。
You don't need to stringify anything to put it in
settings.data
. Thedata
is:What you're doing is putting this string:
into
data
but that string is not a query string so things are going to get confused. You should be able to simply assign your JavaScript object tosettings.data
:and let jQuery sort it out from there.
Update based on evidence rather than documentation:
However, further investigation reveals that this doesn't work. If I send a GET request, any changes I make to
settings.data
are ignored but if I send a POST request, then changes tosettings.data
stick but you have to use the query string format to get anything sensible through:The version of
settings.data
combined with a POST request gets me this:on the server and that looks like what you're after. If you want to preserve some of the original parameters then you'll have to unpack and repack the query string by hand.